正则表达式 - 2 个完整单词之间的全局搜索

发布于 2024-11-09 04:13:04 字数 542 浏览 5 评论 0原文

我正在尝试使用正则表达式搜索两个完整单词之间的内容。例如:

所有的女孩都去了商场 镇。

在上面的字符串中,我想查找单词 allto 之间的内容:

(?<=all).*?(?=to)/g

但是,它找到了两个匹配项,因为没有指示表达式仅在整个单词之间进行搜索:

" the girls went " //between all and to
" in " //between m(all) and (to)wn

我曾想过在表达式中添加空格,如下所示:

(?<= all ).*?(?= to )/g

但这在上面的字符串中不起作用,因为 all 是句子的第一个单词。

如何编写表达式,以便它仅在 2 个完整单词之间找到所有适当的内容,而没有部分单词匹配,如示例所示?

I'm attempting to search for content between 2 whole words using a regular expression. For example:

all the girls went to the mall in
town.

In the above string I want to find the content between the word all and to:

(?<=all).*?(?=to)/g

However, it's finding two matches since the expression is not instructed to search between whole words only:

" the girls went " //between all and to
" in " //between m(all) and (to)wn

I had thought to add spaces in the expression, like this:

(?<= all ).*?(?= to )/g

but this will not work in the above string since all is the first word of the sentence.

How can I write the expression so that it finds all appropriate content between 2 whole words only, without partial word matches as shown in the example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

看透却不说透 2024-11-16 04:13:04

添加字边界

(?<=\ball\b).*?(?=\bto\b)

\b 是无宽度字边界。它匹配单词的开头或结尾(当然,由正则表达式定义)

Add word boundaries

(?<=\ball\b).*?(?=\bto\b)

\b is a no-width word boundary. It matches the beginning or end of a word (as defined by regex, of course)

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