[英]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-789
或q-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]
. 如果要匹配r
或R
,只需在字符类中替换它们: ^[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.