Regular Expression - Global Search Between 2 Whole

2019-05-30 19:27发布

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条回答
迷人小祖宗
2楼-- · 2019-05-30 19:56

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)

查看更多
登录 后发表回答