Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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)

like image 268
JediPotPie Avatar asked Mar 19 '09 21:03

JediPotPie


People also ask

How do you find repeated characters?

An efficient solution is to use Hashing to solve this in O(N) time on average. Create an empty hash. Scan each character of input string and insert values to each keys in the hash. When any character appears more than once, hash key value is increment by 1, and return the character.

How do I find special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do I check if a string has repeated characters?

If we want to know whether a given string has repeated characters, the simplest way is to use the existing method of finding first occurrence from the end of the string, e.g. lastIndexOf in java. In Python, the equivalence would be rfind method of string type that will look for the last occurrence of the substring.


2 Answers

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)

like image 103
David Z Avatar answered Oct 27 '22 00:10

David Z


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)); } 
like image 42
Simon Nickerson Avatar answered Oct 26 '22 22:10

Simon Nickerson