简体   繁体   中英

Javascript Regex partial matching

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!

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

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM