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