Regex detect any repeated character but with optio

2019-07-04 21:37发布

问题:

So currently I've got the following regex pattern, allowing me to detect any string containing 9 characters that are the same consecutively.

/^.*(\S)\1{9,}.*$/

This works perfectly with a string like the following: this a tesssssssssst however I wish for it to also detect a string like this: this a tess sss ssssst (Same number of the repeated character, but with optional whitespace)

Any ideas?

回答1:

You need to put the backreference into a group and add an optional space into the group:

^.*(\S)(?: ?\1){9,}.*$

See the regex demo. If there can be more than 1 space in between, replace ? with *.

The .*$ part is only needed if you need to get the whole line match, for methods that allow partial matches, you may use ^.*(\S)(?: ?\1){9,}.

If any whitespace is meant, replace the space with \s in the pattern.



回答2:

You can check more than a single character this way.
It's only limited by the number of capture groups available.

This one checks for 1 - 3 characters.

(\S)[ ]*(\S)?[ ]*(\S)?(?:[ ]*(?:\1[ ]*\2[ ]*\3)){9,}

http://regexr.com/3g709

 # 1-3 Characters
 ( \S )                        # (1)
 [ ]* 
 ( \S )?                       # (2)
 [ ]* 
 ( \S )?                       # (3)
 # Add more here

 (?:
      [ ]* 
      (?: \1 [ ]* \2 [ ]* \3 )
      # Add more here
 ){9,}