Javascript正则表达式模式匹配单个字符串的多个字符串(AND,OR)

Q S*_*dio 5 javascript regex match

我需要根据一个相当复杂的查询过滤一个字符串集合 - 在它的"原始"形式中它看起来像这样:

nano* AND (regulat* OR *toxic* OR ((risk OR hazard) AND (exposure OR release)) )
Run Code Online (Sandbox Code Playgroud)

要匹配的字符串之一的示例:

Workshop on the Second Regulatory Review on Nanomaterials, 30 January 2013, Brussels
Run Code Online (Sandbox Code Playgroud)

所以,我需要匹配使用AND OR和通配符 - 所以,我认为我需要在JavaScript中使用正则表达式.

我已经正确地循环,过滤和一般工作,但我100%确定我的正则表达式是错误的 - 并且一些结果被错误地省略 - 这里是:

/(nano[a-zA-Z])?(regulat[a-zA-Z]|[a-zA-Z]toxic[a-zA-Z]|((risk|hazard)*(exposure|release)))/i
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激 - 我真的无法正确地理解这个语法!

更新:

很少有人指出构造正则表达式的顺序的重要性,但是我无法控制将要搜索的文本字符串,所以我需要找到一个无论顺序如何都可以工作的解决方案.

更新:

最终使用了PHP解决方案,由于twitter API 1.0的弃用,请参见pastebin示例函数(我知道最好在这里粘贴代码,但是有很多......):

功能:http://pastebin.com/MpWSGtHK 用法:http://pastebin.com/pP2AHEvk

谢谢你的帮助

Tim*_*ker 22

单一的正则表达式不适合这个,IMO:

/^(?=.*\bnano)(?=(?:.*\bregulat|.*toxic|(?=.*(?:\brisk\b|\bhazard\b))(?=.*(?:\bexposure\b|\brelease\b))))/i.test(subject))
Run Code Online (Sandbox Code Playgroud)

如果字符串满足你提出的标准,它将返回True,但我发现嵌套的前瞻是非常难以理解的.如果JavaScript支持注释的正则表达式,它将如下所示:

^                 # Anchor search to start of string
(?=.*\bnano)      # Assert that the string contains a word that starts with nano
(?=               # AND assert that the string contains...
 (?:              #  either
  .*\bregulat     #   a word starting with regulat
 |                #  OR
  .*toxic         #   any word containing toxic
 |                #  OR
  (?=             #   assert that the string contains
   .*             #    any string
   (?:            #    followed by
    \brisk\b      #    the word risk
   |              #    OR
    \bhazard\b    #    the word hazard
   )              #    (end of inner OR alternation)
  )               #   (end of first AND condition)
  (?=             #   AND assert that the string contains
   .*             #    any string
   (?:            #    followed by
    \bexposure\b  #    the word exposure
   |              #    OR
    \brelease\b   #    the word release
   )              #    (end of inner OR alternation)
  )               #   (end of second AND condition)
 )                #  (end of outer OR alternation)
)                 # (end of lookahead assertion)
Run Code Online (Sandbox Code Playgroud)

请注意,整个正则表达式由前瞻断言组成,因此匹配结果本身将始终为空字符串.

相反,您可以使用单个正则表达式:

if (/\bnano/i.test(str) &&
    ( 
        /\bregulat|toxic/i.test(str) ||
        ( 
            /\b(?:risk|hazard)\b/i.test(str) &&
            /\b(?:exposure|release)\b/i.test(str)
        )
    )
)    /* all tests pass */
Run Code Online (Sandbox Code Playgroud)