Home > front end >  Using RegExp to test words for letter count
Using RegExp to test words for letter count

Time:03-09

I've been trying to use RegExp in JS to test a string for a certain count of a substrings. I would like a purely RegExp approach so I can combine it with my other search criteria, but have not had any luck.

As a simple example I would like to test a word if it has exactly 2-3 as.

case test string expected result
1 cat false
2 shazam true
3 abracadabra false

Most of my guesses at regex fail case 3. Example: ^(?<!.*a.*)((.*a.*){2,3})(?!.*a.*)$

CodePudding user response:

Could use this regex.

With any other character, including whitespace.

^[^a]*(?:a[^a]*){2,3}$

or if using multi-lines and don't want to span.

^[^a\r\n]*(?:a[^a\r\n]*){2,3}$

^                  # Begin 
[^a]*              # optional not-a
(?:                # Grp
  a                  # single a
  [^a]*              # optional not-a
){2,3}             # Get 2 or 3 a only
$                  # End

https://regex101.com/r/O3SYKx/1

  • Related