正则表达式中的^和$是什么意思?
"\\w+@\\w+[.]\\w+"
和 "^\\w+@\\w+[.]\\w+$"
之间有什么区别代码>?我尝试用谷歌搜索它,但没有成功。
What is the difference between "\\w+@\\w+[.]\\w+"
and "^\\w+@\\w+[.]\\w+$"
? I have tried to google for it but no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
^
表示“匹配字符串的开头”(更准确地说,是字符串中第一个字符之前的位置,因此它与实际字符不匹配)。$
表示“匹配字符串的末尾”(字符串中最后一个字符之后的位置)。两者都称为 anchors 并确保匹配整个字符串而不仅仅是子字符串。
因此,在您的示例中,第一个正则表达式将报告
[email protected] 上的匹配项
,但匹配的文本将是[电子邮件受保护]
,可能不是您想要的预期的。第二个正则表达式将会失败。请小心,因为某些正则表达式实现隐式地将正则表达式锚定在字符串的开头/结尾(例如 Java 的
.matches()
,如果您正在使用它)。如果设置了多行选项(例如,使用
(?m)
标志,或者通过执行Pattern.compile("^\\w+@\\w+[.]\\w+ $", Pattern.MULTILINE)
),则^
和$
也会在行的开头和结尾匹配。^
means "Match the start of the string" (more exactly, the position before the first character in the string, so it does not match an actual character).$
means "Match the end of the string" (the position after the last character in the string).Both are called anchors and ensure that the entire string is matched instead of just a substring.
So in your example, the first regex will report a match on
[email protected]
, but the matched text will be[email protected]
, probably not what you expected. The second regex will simply fail.Be careful, as some regex implementations implicitly anchor the regex at the start/end of the string (for example Java's
.matches()
, if you're using that).If the multiline option is set (using the
(?m)
flag, for example, or by doingPattern.compile("^\\w+@\\w+[.]\\w+$", Pattern.MULTILINE)
), then^
and$
also match at the start and end of a line.尝试 Javadoc:
http://download.oracle .com/javase/6/docs/api/java/util/regex/Pattern.html
^
和$
匹配行的开头/结尾(而不消耗它们)Try the Javadoc:
http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
^
and$
match the beginnings/endings of a line (without consuming them)