Use regex to match consecutively repeated characters: \1

Given a string, how to judge whether it contains consecutive repeated letters (a-zA-Z), return true if it contains; otherwise return false

example result Remark
‘rattler’ true The repetition is two English letters tt
'ra11ler' false The duplicates are two numbers 11, which do not meet the conditions

Code:

function containsRepeatingLetter(str) {
    
    
    let reg = /([a-zA-Z])\1/
    return reg.test(str);
}

Parse:

  1. [a-zA-Z]is to match a single letter
  2. \1is to match letters that repeat the first set of content
  3. There is only one group here, and it matches a single letter, the result is to match consecutive repeated letters, such as cc in abcc

Good article link: here

The best summary of the article:

This \1 \2... must be used together with the regular expression set ()
 
\1 means repeat the content matched in the first parenthesis of the
regular regular \2 means repeat the content matched in the second parenthesis of the regular regular

If you only want to match consecutive characters of a certain type, such as letters and numbers, no repetition is required, just use the +?*{}equal qualifier:
insert image description here

Guess you like

Origin blog.csdn.net/qq_43523725/article/details/119377617