Regular Expression - Global Search Between 2 Whole Words

风流意气都作罢 提交于 2020-01-03 02:54:12

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/6079243/regular-expression-global-search-between-2-whole-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!