Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i write the regex "All characters are the same"?

Tags:

java

regex

I would like it to match:

aaaaaa
bb
c

but not:

aaabaaa
cd

...

like image 775
Julio Faerman Avatar asked Jul 15 '10 17:07

Julio Faerman


2 Answers

Assuming the regex engine supports back-references,

^(.)\1*$

In Java it would be

theString.matches("(.)\\1*")
like image 144
kennytm Avatar answered Oct 06 '22 02:10

kennytm


Using back references:

(.)(\1)*

Read: match any character followed by that same character 0 or more times.

Depending on the regexp engine and your needs, you might want to anchor the regex to only match the whole string, not substrings.

like image 33
sepp2k Avatar answered Oct 06 '22 02:10

sepp2k