JediPotPie
JediPotPie

Reputation: 1068

How can I find repeated characters with a regex in Java?

Can anyone give me a Java regex to identify repeated characters in a string? I am only looking for characters that are repeated immediately and they can be letters or digits.

Example:

abccde <- looking for this (immediately repeating c's)

abcdce <- not this (c's seperated by another character)

Upvotes: 22

Views: 52930

Answers (3)

Simon Nickerson
Simon Nickerson

Reputation: 43177

String stringToMatch = "abccdef";
Pattern p = Pattern.compile("(\\w)\\1+");
Matcher m = p.matcher(stringToMatch);
if (m.find())
{
    System.out.println("Duplicate character " + m.group(1));
}

Upvotes: 13

John Terry
John Terry

Reputation:

Regular Expressions are expensive. You would probably be better off just storing the last character and checking to see if the next one is the same. Something along the lines of:

String s;
char c1, c2;
c1 = s.charAt(0);
for(int i=1;i<s.length(); i++){
    char c2 = s.charAt(i);

    // Check if they are equal here

    c1=c2;
}  

Upvotes: -6

David Z
David Z

Reputation: 131790

Try "(\\w)\\1+"

The \\w matches any word character (letter, digit, or underscore) and the \\1+ matches whatever was in the first set of parentheses, one or more times. So you wind up matching any occurrence of a word character, followed immediately by one or more of the same word character again.

(Note that I gave the regex as a Java string, i.e. with the backslashes already doubled for you)

Upvotes: 41

Related Questions