Double Characters in Regular Expressions

Asked

Viewed 375 times

5

I’m training my javascript and I’m wondering how I look for repeated characters in a regular expression

Example: I type aa in a textbox and, within a validation method, the method checks whether the character a, typed twice in a row, is inside Regexp

  • Accept the answer if it solves your problem :)

1 answer

4

What you want to do would need something called backreference (http://www.regular-expressions.info/backref.html), where one refers to a previously captured group within the regular expression. It would have this face:

(.)\1

That is to say:

  • (.) Match any character and create a group
  • \1 Find the character you just found again

You can mix that with + or the repeating ranges {min,max} to make any match:

(.)\1{2,4}
  • (.) Right above
  • \1{2,4} Match in 3 to 5 repeated characters

Or:

(.)\1{2}
  • (.) Right above
  • \1{2} Match in exactly 2 repeated characters

Or:

(.)\1+
  • (.) Right above
  • \1+ Match in 2 or more repeated characters

If you want to be more specific (you are only looking for repetitions of space characters, for example), just change the group (.) for what I would like to find repeated.


In code:

function hasRepetition(str) {
  return /(.)\1/.test(str);
}

hasRepetition('best') // false
hasRepetition('beest') // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.