正则表达式中的^和$是什么意思?

发布于 2024-11-27 13:51:46 字数 105 浏览 4 评论 0原文

"\\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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

微凉 2024-12-04 13:51:46

^ 表示“匹配字符串的开头”(更准确地说,是字符串中第一个字符之前的位置,因此它与实际字符不匹配)。

$ 表示“匹配字符串的末尾”(字符串中最后一个字符之后的位置)。

两者都称为 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 doing Pattern.compile("^\\w+@\\w+[.]\\w+$", Pattern.MULTILINE)), then ^ and $ also match at the start and end of a line.

治碍 2024-12-04 13:51:46

尝试 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文