Regex to determine if string is a single repeating character [duplicate]

て烟熏妆下的殇ゞ 提交于 2020-01-11 09:24:06

问题


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.


回答1:


You can try with back reference

^(.)\1{1,}$

DEMO

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.




回答2:


this really depends on your language but in general this would match a line with all the same character.

^(.)\1+$

Regex101 Example

  • ^ 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

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