Regex to determine if a string is a single repeated character

What is a regular expression pattern to determine if a string consists of only one repeating character?

eg.

"aaaaaaa" = true
"aaabbbb" = false
"$$$$$$$" = true

This question checks if a string contains only repeated characters (for example, "aabb"), however I need to determine if it is a single repeated character.

+2
source share
2 answers

You can try the backlink

^(.)\1{1,}$

Demo

Sample 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 , . \1 ( ) . \1 , .


Java

"aaaaaaaa".matches("(.)\\1+") // true

^ $, String.matches() .

+5

, .

^(.)\1+$

Regex101

  • ^
  • 1- (.)
  • \1+ , : + , , []
  • $
+4

Source: https://habr.com/ru/post/1627618/


All Articles