Regex - finding all 3 letter words - unexpected outcome

后端 未结 1 441
星月不相逢
星月不相逢 2021-01-27 04:28

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{         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 04:51

    (?<=\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.

    0 讨论(0)
提交回复
热议问题