문제

I Want to know if a String consists only of the same character except at the last index, it can be any other possible character except the character that's leading. For Example: "FFFFFFFl" matches the pattern, but "FlFFFF" not.

If the String is only one Character, it should output false.

I have this code, but actually it's not working:

String dance = "FFFFFl";
Pattern p = Pattern.compile(dance.charAt(0) + "{" + (dance.length()-1) + "}\\w^" + dance.charAt(0));
Matcher m = p.matcher(dance);
System.out.println(m.matches());

This outputs "false" even though it should be true. I would really appreciate your help!

도움이 되었습니까?

해결책

Pattern p = Pattern.compile("^(.)\\1*+.$");

Match:

AF
AAAAAF

Don't match:

AAAA
AFFFF

다른 팁

Pattern: "^(.)\\1*+.$"

See java reference

The following does not work I just found out:

if (dance.matches("(.)\\1*(!\\1)"))

where \\1 is the first group (the first char).

Your approach:

dance.charAt(0) + "{" + (dance.length()-1) + "}[^" + dance.charAt(0) + "]"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top