简体   繁体   English

奇怪的结果与简单的正则表达式

[英]Strange result with a simple regular expression

I'm working on regular expressions right now and experience a strange behavior: 我正在研究正则表达式并遇到一种奇怪的行为:

The following regex accepts Q-123456-789 or q-123456-789 以下正则表达式接受Q-123456-789q-123456-789

params: '^\\q\\-\\d{6}\\-\\d{3}$|^\\Q\\-\\d{6}\\-\\d{3}$'

The following regex accepts R-123456-789 but not r-123456-789 以下正则表达式接受R-123456-789但不接受r-123456-789

params: '^\\r\\-\\d{6}\\-\\d{3}$|^\\R\\-\\d{6}\\-\\d{3}$'

(I simply replaced q by r and Q by R ) (我只是用r代替q ,用R代替Q

Because: 因为:

\\r matches a carriage return \\r匹配回车

but \\q matches literal q only. 但是\\q q仅匹配文字q

Btw your regex is using excessive escaping, it should be without \\\\ ie 顺便说一句,你的正则表达式使用过度转义,它应该没有\\\\ ie

"^[qQ]-\\d{6}-\\d{3}$"

OR 要么

"^[rR]-\\d{6}-\\d{3}$"

\\r matches a carriage return (0x0D - a non printable character), not the r character. \\r匹配回车符 (0x0D - 不可打印的字符),而不是r字符。 whereas \\q does match the character q . \\q确实匹配字符q

If you want to match r or R , simply replace them in a character class: ^[rR] . 如果要匹配rR ,只需在字符类中替换它们: ^[rR]

Try [r] for exact match instead of \\r for expected result 尝试[r]进行精确匹配,而不是\\r得到预期结果

Try this: 尝试这个:

^[rR]-\d{6}\-\d{3}$

Use https://regex101.com/#javascript for testing 使用https://regex101.com/#javascript进行测试

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

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