Krullmizter
Krullmizter

Reputation: 567

Javascript regex - check if string contains two or more of same letter

I'm working on some regex with JavaScript. I have now created a regex that checks if a string has two or more of the same letter following each other. I would want to create a regex that checks if a word / string contains two or more of one particular letter, no matter if they are after each other or just in the same word / string.

It would need to match: drama and anaconda, but not match: lame, kiwi or tree.

This is the regex in JS.

const str = "anaconda"; 
str.match(/[a]{2,}/);

Upvotes: 1

Views: 2397

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18641

Use

\w*(\w)\w*\1\w*

See proof

EXPLANATION

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  \w*                      word characters (a-z, A-Z, 0-9, _) (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \w                       word characters (a-z, A-Z, 0-9, _)
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \w*                      word characters (a-z, A-Z, 0-9, _) (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \1                       what was matched by capture \1
--------------------------------------------------------------------------------
  \w*                      word characters (a-z, A-Z, 0-9, _) (0 or
                           more times (matching the most amount
                           possible))

Upvotes: 2

shubhushan shambhu
shubhushan shambhu

Reputation: 41

My thought process was something like this:

  1. A word can start with any Alphabet
  2. A word can end with any Alphabet
  3. Similar letters can have zero or multiple alphabets between them
  4. If any of it's letters are similar and it fits the criteria above then accept the word
     regex = /[a-z]*([a-z])[a-z]*\1+[a-z]*/

Upvotes: 0

Related Questions