本文介绍了正则表达式-2个完整单词之间的全局搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

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?

推荐答案

添加单词边界

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

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

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

这篇关于正则表达式-2个完整单词之间的全局搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 21:50