【问题标题】:Using regex to match combination of words in the same in the same sentence in PHP使用正则表达式匹配PHP中同一句子中相同单词的组合
【发布时间】:2014-12-24 21:44:42
【问题描述】:

我想使用正则表达式从 php 中的短语中查找某些单词组合。我什至无法让正则表达式部分工作。

该句子应与同一句子中包含 (chinese/mandarin/cantonese) 中的单词 (proficient/proficiency/fluent) 的任何短语匹配。所以它会匹配“她会说流利的中文”。和“他的普通话水平非常好”

regex = (fluent)|(proficient)|(proficiency).*(chinese)|(mandarin)|(cantonese)

我可以让它匹配 fluent 这个词,但是如何让它匹配同一个句子中的两个词,然后才被认为是匹配?

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你的分组是错误的,应该是这样

    (fluent|proficient|proficiency)[^.]*(chinese|mandarin|cantonese)
    

    [^.] 确保(天真地)单词出现在同一个句子中。另外,不要忘记 i 标志来匹配标题大小写的单词,如 Chinese

    【讨论】:

      【解决方案2】:
      ((fluent)|(proficient)|(proficiency)).*((chinese)|(mandarin)|(cantonese))
      

      你需要加上括号,如果你还想匹配整个句子你需要做这样的事情

      [.!?].*((fluent)|(proficient)|(proficiency)).*((chinese)|(mandarin)|(cantonese)).*[.!?]
      

      【讨论】:

        【解决方案3】:

        如果顺序无关紧要,您可以使用两个正则表达式,第一个用于第一组,第二个用于匹配第二组。比你匹配两次,如果都命中,你就成功了。

        如果您正在处理流利的文本,我会尝试将其拆分成句子。

        【讨论】:

          猜你喜欢
          • 2010-12-29
          • 1970-01-01
          • 1970-01-01
          • 2011-04-10
          • 2013-01-23
          • 2021-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多