简体   繁体   English

正则表达式 - 匹配取决于第一个字符

[英]Regex - match depending of the first character

I'm trying to create the perfect regex for matching these results:我正在尝试创建完美的正则表达式来匹配这些结果:

NC1014 C599 NC1014 C599

"NC" followed by 4 digits, or "C" followed by 3 digits. “NC”后跟 4 位数字,或“C”后跟 3 位数字。

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.但是如果我测试“NC1200”,它就不起作用,它只能识别里面的“C120”。
The problem is that if I test "NC100" it works too, and it should not.问题是如果我测试“NC100”它也可以工作,但它不应该。

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.此外, [NC]表示NC ,您需要NC代替。

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? /NC[\d]{4}\b|C[\d]{3}\b/gm完美运行,为什么 C 后面有 2 或 3 位数字? Also, [NC] will search for either a single N or C.此外, [NC]将搜索单个 N 或 C。 Note that each match ends in a \b flag to prevent a match like NC12345 = NC1234.请注意,每个匹配都以\b标志结束,以防止像 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 /N?C\d{3,4}/gm匹配一行中的两个表达式(不分组),例如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. /^NC\d{4}|C\d{3}$/gm匹配行首的NC1200和行尾的C599 ,这可能最接近您的初始尝试。

BTW: do you know regex101.com where you can test your regex?顺便说一句:你知道regex101.com在哪里可以测试你的正则表达式吗? This might be quite helpful.这可能很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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