正则表达式 - 找到所有 3 个字母的单词 - 意想不到的结果 [英] Regex - finding all 3 letter words - unexpected outcome

查看:69
本文介绍了正则表达式 - 找到所有 3 个字母的单词 - 意想不到的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用regexpal.com 练习我的正则表达式.我决定简单开始,但遇到了问题.

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

假设您要查找所有 3 个字母的单词.

Say you want to find all 3 letter words.

\s\w{3}\s

\s - 空格

\w - 单词字符

{3} - 3 个且仅前一个字符的 3 个

{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 ".

推荐答案

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

重叠空间.改为使用 0 宽度断言.当您在"abc acd "上使用 \s\w{3}\s 时,正则表达式引擎消耗 abc 所以唯一剩下的就是 acd 您的正则表达式将不匹配.所以使用 lookaround 只是断言而不是消费.

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.

\b\w{3}\b

也可以使用.

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

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

这将找到您的 3 个字母的单词,即使它位于开头、中间或结尾.

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

这篇关于正则表达式 - 找到所有 3 个字母的单词 - 意想不到的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆