Javascript Regex partial matching

846 views Asked by At

I'm looking for a simple javascript regex that should match strings like

AAAA(abcd,6) 
AAAA(WXYZ,2) 

but should not match strings like

AAAA(abcd,6,9)

I've come up withe the regex

AAAA\(.*,\d\)

but it matches all three of above.

Any help is much appreciated!

Thanks in advance!

3

There are 3 answers

0
SoEzPz On
var regex = /AAAA\([a-z]*,\d\)/i;

regex.test("AAAA(abcd,6)") => true;

regex.test("AAAA(WXYZ,2)") => true;

regex.test("AAAA(abcd,6,9)") => false;
4
Adassko On

That's because .* will match anything including ,6 Replace . with [^,] (any char but comma)

AAAA\([^,]*,\d\)

1
Robin On

Depending on exactly what you want to match you could use something like

A{4}\([a-zA-Z]{4},\d\)
  • A{4} matches the character A exactly 4 times.
  • \( matches the character (
  • [a-zA-Z]{4} matches any lower or upper case character from a to z exactly 4 times.
  • , matches the character ,
  • \d matches a digit.
  • \) matches the character )

You could of course modify it to suit your needs, I recommend testing for instance at regex101 since it gives you instant feedback when you enter a regular expression.