Mayo
Mayo

Reputation: 379

Regex - finding all 3 letter words - unexpected outcome

Using regexpal.com to practice my regular expressions. I decided to start simply and ran into a problem.

Say you want to find all 3 letter words.

\s\w{3}\s

\s - space

\w - word characters

{3} - 3 and only 3 of the previous character

\s

If I have two three letter words next to each other example " and the " only the first is selected. I thought that after a regex found a match it would go back one character and start searching for the next matching string. (In which case it would "find" both " and " & " the ".

Upvotes: 1

Views: 3210

Answers (1)

vks
vks

Reputation: 67968

(?<=\s)\w{3}(?=\s)

Overlapping spaces. Use 0 width assertions instead.When you use \s\w{3}\s on " abc acd " the regex engine consumes abc so the only thing left is acd which your regex will not match.So use lookaround to just assert and not consume.

EDIT:

\b\w{3}\b

Can also be used.

\b==>assert position at a word boundary (^\w|\w$|\W\w|\w\W)

or

(?:^|(?<=\s))\w{3}(?=\s|$)

This will find your 3 letter word even if it is at start or in middle or at end.

Upvotes: 3

Related Questions