-3

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!

Dwithin D
  • 11
  • 2

3 Answers3

2

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

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

Adassko
  • 5,201
  • 20
  • 37
  • jslint complains about negative classes because they match so much. its usually faster and more reliable to be more specific if possible. – dandavis Jun 17 '15 at 08:14
  • And that would find any character but `,`. If there are only letters to be matched than it is better to go with `\w+` or `\w{4}` for exactly 4 letters. – cezar Jun 17 '15 at 08:16
  • 1
    but we don't know what the possible characters are. Author can be more specific – Adassko Jun 17 '15 at 08:16
  • @Adassko yes, you're right. It is hard to guess what the author exactly means and we can't read thoughts :) – cezar Jun 17 '15 at 08:21
1

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.

Robin
  • 1,251
  • 11
  • 18
  • I don't think there's any pros of replacing `AAAA` with `A{4}` - it's much less readable for me. I would leave `AAAA` as it is – Adassko Jun 17 '15 at 08:19
0
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;
SoEzPz
  • 14,958
  • 8
  • 61
  • 64