正则表达式:匹配 3 个连续的单词 [英] regex: matching 3 consecutive words

查看:91
本文介绍了正则表达式:匹配 3 个连续的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查看一个字符串是否包含 3 个连续的单词(用空格分隔且没有数字),但我构建的正则表达式似乎不起作用:

I'm trying to see if a string contains 3 consecutive words (divided by spaces and without numbers), but the regex I have constructed does not seem to work:

print re.match('([a-zA-Z]+\b){3}', "123 test bla foo")
None

这应该返回 true,因为字符串包含 3 个单词test bla foo".

This should return true since the string contains the 3 words "test bla foo".

实现这一目标的最佳方法是什么?

What is the best way to achieve this?

推荐答案

做:

(?:[A-Za-z]+ ){2}[A-Za-z]+

  • (?:[A-Za-z]+ ){2}:未捕获组(?:[A-Za-z]+ ) 匹配一个或多个后跟空格的字母字符,{2} 匹配两个这样连续的组

    • (?:[A-Za-z]+ ){2}: the non-captured group (?:[A-Za-z]+ ) matches one or more alphabetic characters followed by space, {2} matches two such successive groups

      [A-Za-z]+ 匹配前两个单词后的一个或多个字母字符,成为第三个单词

      [A-Za-z]+ matches one or more alphabetic character after the preceding two words, making the third word

      演示

      如果您希望单词被任何空格分隔而不仅仅是空格:

      If you want the words to be separated by any whitespace instead of just space:

      (?:[A-Za-z]+\s){2}[A-Za-z]+
      

      这篇关于正则表达式:匹配 3 个连续的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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