This question already has an answer here:
- Remove repeating character 3 answers
What is the regex pattern to determine if a string solely consists of a single repeating character?
e.g.
"aaaaaaa" = true
"aaabbbb" = false
"$$$$$$$" = true
This question checks if a string only contains repeating characters (e.g. "aabb") however I need to determine if it is a single repeating character.
You can try with back reference
^(.)\1{1,}$
Pattern Explanation:
^ the beginning of the string
( group and capture to \1:
. any character except \n
) end of \1
\1{1,} what was matched by capture \1 (at least 1 times)
$ the end of the string
Backreferences match the same text as previously matched by a capturing group. The backreference \1
(backslash one) references the first capturing group. \1
matches the exact same text that was matched by the first capturing group.
In Java you can try
"aaaaaaaa".matches("(.)\\1+") // true
There is no need for ^
and $
because String.matches()
looks for whole string match.
this really depends on your language but in general this would match a line with all the same character.
^(.)\1+$
^
assert position at start of a line- 1st Capturing group
(.)
\1+
matches the same text as most recently matched by the 1st capturing group Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]$
assert position at end of a line
来源:https://stackoverflow.com/questions/29158996/regex-to-determine-if-string-is-a-single-repeating-character