Reputation: 6743
Let's say I have this string: fffooooobbbbaarrr
.
Given a number N, for each duplicated characters, I want to display N of them.
If N=2, the output is ffoobbaarr
If N=3, the output is fffooobbbaarrr
If N=1, the output is fobar
And if N=0, the output is (empty)
As I'm learning regex, after some experimentation, I found that this works for N=2:
Pattern pattern = Pattern.compile("(\\w)\\1{2,}");
System.out.println(pattern.matcher(input.replaceAll("$1$1"));
Of course, won't work for N=3, 4, etc. How to fix this?
Upvotes: 4
Views: 91
Reputation: 785721
You can use this regex replacement:
int n = 3 // or whatever number;
String repl = "";
if (n > 0) {
repl = str.replaceAll("((\\S)\\2{" + (n-1) + "})\\2*", "$1");
}
Example: (for N=3)
Example: (for N=2)
Explanation:
(
: Start capture group #1(\S)
: Match 1+ non-whitespace char and capture as group #2\2{2}
: Match 2 instances of same char)
: End capture group #1\2*
: Match 0+ instances of same character outside capture groupUpvotes: 3
Reputation: 48751
Use below regex as looker:
(\\w)(\\1{N})\\1*
Breakdown:
(\w)
Match and capture a letter to capturing group 1(\1{N})
Match previous captured letter N
times (capturing group 2)\1*
Match any number of following repetitionsN is the number of letters you need to retain (you could use it as a variable. 0
results an empty output) and for replacement use:
$2
Java code (demo):
String str = "fffooooobbbbaarrr";
int N = 3;
str = str.replaceAll("(\\w)(\\1{" + N + "})\\1*", "$2");
System.out.println(str); // fffooobbbaarrr
Upvotes: 1
Reputation: 60046
You can Pattern and matcher like this :
String text = "fffooooobbbbaarrr";
Pattern pattern = Pattern.compile("(.)\\1*");
Matcher matcher = pattern.matcher(text);
String result = "";
int len = 3;
while (matcher.find()) {
if(matcher.group().length() >= len) {
result += matcher.group().substring(0, len);
}else {
result += matcher.group();
}
}
System.out.println(result);
Result :
3 --> fffooobbbaarrr
2 --> ffoobbaarr
1 --> fobar
0 --> empty
The idea is :
(.)\1*
zero or more time Upvotes: 1