1

I want to replaceAll strings like:

"aaaa"
"zzzzzzz"
"----------"
"TTTTTT"
"...."

String contains only one char, but > 3 times.

I use Java. I can replace a specific char (like "a") with more than 3 times, but don't know how to do this with any char:

str = str.replaceAll("^[a]{4,}$", "");

Any idea? If this can't be done in regex, how would you do it?

2
  • 1
    Any char? Use "(?s)^(.)\\1{3,}$". Commented Nov 26, 2015 at 10:56
  • Seems to work, thanks! :-) Can you please explain it? Commented Nov 26, 2015 at 11:03

1 Answer 1

3

Any char can be matched with . and Pattern.DOTALL modifier.

To check if it is the same, we can capture the first character and use a backreference to match the same text, and a limiting quantifier {3,} to check for at least 3 occurrences of the same substring.

See a regex and IDEONE demo:

List<String> strs = Arrays.asList("aaaa", "zzzzzzz", "----------", "TTTTTT", "....");
for (String str : strs)
    System.out.println("\"" + str.replaceAll("(?s)^(.)\\1{3,}$", "") + "\"");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.