How can i write the regex “All characters are the same”?

▼魔方 西西 提交于 2021-02-04 13:32:09

问题


I would like it to match:

aaaaaa
bb
c

but not:

aaabaaa
cd

...


回答1:


Assuming the regex engine supports back-references,

^(.)\1*$

In Java it would be

theString.matches("(.)\\1*")



回答2:


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.




回答3:


If you want to capture what you match, it is ^((.)\2*)$




回答4:


Just for contributing to this question, you can use the BackRefence:

(\w+)\s+\1

It checks repeated words separated by whitespace.



来源:https://stackoverflow.com/questions/3258444/how-can-i-write-the-regex-all-characters-are-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!