Chunky Chunk
Chunky Chunk

Reputation: 17237

Regular Expression - Global Search Between 2 Whole Words

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?

Upvotes: 2

Views: 995

Answers (1)

Sylver
Sylver

Reputation: 8968

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)

Upvotes: 3

Related Questions