简体   繁体   中英

Regex - match depending of the first character

I'm trying to create the perfect regex for matching these results:

NC1014 C599

"NC" followed by 4 digits, or "C" followed by 3 digits.

I tried this expression

/^[NC]\d{4}|[C]\d{2,3}$/

but if I test "NC1200", it doesn't work, it only recognizes "C120" inside.
The problem is that if I test "NC100" it works too, and it should not.

Do you have any idea?

The problem with your regex is that | has the highest priority, so the start anchor is part of the first branch, and the end anchor is part of the second branch, but they're never together. Also, [NC] means N or C , you want NC instead.

With both of these in mind, try this:

^(NC\d{4}|C\d{3})$

how about this?

/^(NC)\d{4}|[C]\d{2,3}$/

/NC[\d]{4}\b|C[\d]{3}\b/gm works perfectly, why 2 or 3 digits after C? Also, [NC] will search for either a single N or C. Note that each match ends in a \b flag to prevent a match like NC12345 = NC1234.

 const rgx = /NC[\d]{4}\b|C[\d]{3}\b/gm; const str = `C23 NC1014 C599 NC1200 C1866`; console.log([...str.matchAll(rgx)].flat());

/N?C\d{3,4}/gm matches both expressions (without grouping) in a line eg NC1200 C599

/^NC\d{4}|C\d{3}$/gm matches NC1200 at the beginning of a line and C599 at the end of the line which is probably closest to your initial try.

BTW: do you know regex101.com where you can test your regex? This might be quite helpful.

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