Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using RegExp to test words for letter count

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.*)$

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading