为什么这个没有特殊字符的正则表达式匹配更长的字符串? [英] Why does this regex with no special character match a longer string?
问题描述
我正在使用此方法尝试查找匹配项,例如:
I am using this method to try find a match, in an example:
Regex.Match("A2-TS-OIL", "TS-OIL", RegexOptions.IgnoreCase).Success;
我得到了一个真实的结果.我很困惑.我认为这应该返回 false,因为模式中没有特殊字符.如果我使用 ".+TS-OIL"
,则应该返回 true(.
表示任何,+
表示超过 1).我该怎么做才能得到我需要的东西?
I got a true result. I am confused. I think this should return false since there is no special characters in the pattern. If I use ".+TS-OIL"
, true should be returned (.
for any and +
for more than 1). How should I do to get what I need?
推荐答案
正则表达式匹配不必从输入开始.您可能想要:
A regex match doesn't have to start at begining of the input. You might want:
^TS-OIL
如果您只想在开始时匹配.或者:
if you want to only match at the start. Or:
^TS-OIL$
防止它与 TS-OIL-123 匹配.
to prevent it matching TS-OIL-123.
^
匹配输入的开始,$ 匹配输入的结尾.
^
matches the start of the input, $ matches the end.
我相信在某些地方 ^
和 $
会自动添加(如 Web 验证控件),但它们是例外.
I believe there are some place where the ^
and $
get added automatically (like web validation controls) but they're the exception.
顺便说一句,你可以使用:
btw, you could use:
Regex.IsMatch(...)
在这种情况下,可以节省几次按键操作.
in this case to save a few keystrokes.
这篇关于为什么这个没有特殊字符的正则表达式匹配更长的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!