简体   繁体   English

这个正则表达式有什么问题?

[英]What's wrong with this regular expression?

This is almost certainly something really silly that I've overlooked but I'm stumped.这几乎可以肯定是我忽略的非常愚蠢的事情,但我很难过。 The following C# style expression is supposed to match phones numbers (a limited subset of them, but this is just testing...):以下 C# 样式表达式应该与电话号码匹配(它们的有限子集,但这只是测试......):

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

The search string is as follows:搜索字符串如下:

978-454-0586\r\nother junk\r\nmore junk\r\nhttp://www.google.com\r\n

The expression matches the phone number when in isolation, however not when next to other stuff.该表达式在孤立时与电话号码匹配,但在与其他东西相邻时则不匹配。 For example, if I lop off everything after the phone it works just great.例如,如果我在接完电话后把所有东西都删掉,那效果就很好。

How can I modify the expression so that it matches the phone number and doesn't get hung up on the rest of the junk?如何修改表达式以使其与电话号码匹配并且不会挂断在垃圾邮件的 rest 上?

Thanks!谢谢!

The ^ and $ symbols mean "beginning of line" and "end of line" respectively. ^ 和 $ 符号分别表示“行首”和“行尾”。 Get rid of them if you want to match in the middle of a line.如果您想在一行中间匹配,请摆脱它们。

"$" in a regular expression matches the end of a line.正则表达式中的“$”匹配行尾。 If you remove that, the regexp should work correctly, though if you have "Foo978-454-0586", it won't work, since "^" matches the start of a line.如果你删除它,正则表达式应该可以正常工作,但如果你有“Foo978-454-0586”,它就不会工作,因为“^”匹配一行的开头。

Are the phone numbers always on their own lines?电话号码总是在自己的线路上吗? If so add RegexOptions.Multiline to your Regex constructor.如果是这样,请将 RegexOptions.Multiline 添加到您的 Regex 构造函数中。 Without that the regex.match is using the beginning and end of the string for ^ and $.如果没有,regex.match 将字符串的开头和结尾用于 ^ 和 $。

The $ means end of string, not end of line. $表示字符串的结尾,而不是行尾。

The problem is that "^" and "$" forces it to only match on the start of the string and the end of the string.问题是“^”和“$”强制它只匹配字符串的开头和字符串的结尾。

Remove those two tags and see how you go.去掉这两个标签,看看你的 go 怎么样。

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

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