用于不同单词的正则表达式(未嵌入其他单词)

时间:2014-06-08 09:15:20

标签: ios objective-c regex nsregularexpression

如何创建正则表达式以匹配不同的单词?

我尝试了以下正则表达式,但它也匹配其他单词中嵌入的单词:

@"(abs|acos|acosh|asin|asinh|atan|atanh)"

例如,使用

@"xxxabs abs"

abs本身应匹配,但不在xxxabs内。

1 个答案:

答案 0 :(得分:1)

虽然解决方案(单词边界)是一个古老的经典,但你的问题很有趣,因为交替中的单词非常相似。

你可以从这开始:

\b(?:abs|acos|acosh|asin|asinh|atan|atanh)\b

压缩到那个:

\b(?:a(?:cosh?|sinh?|tanh?|bs))\b

它是如何运作的?

  1. 关键的想法是使用word boundaries \b来确保匹配不会嵌入更大的单词中。
  2. 压缩的想法是使引擎匹配更快。但是,它很难阅读,所以除非你需要最后一滴表演,否则这纯粹是出于娱乐目的。
  3. <强>令牌通过令牌

    \b                       # the boundary between a word char (\w) and
                             # something that is not a word char
    (?:                      # group, but do not capture:
      a                      #   'a'
      (?:                    #   group, but do not capture:
        cos                  #     'cos'
        h?                   #     'h' (optional (matching the most
                             #     amount possible))
       |                     #    OR
        sin                  #     'sin'
        h?                   #     'h' (optional (matching the most
                             #     amount possible))
       |                     #    OR
        tan                  #     'tan'
        h?                   #     'h' (optional (matching the most
                             #     amount possible))
       |                     #    OR
        bs                   #     'bs'
      )                      #   end of grouping
    )                        # end of grouping
    \b                       # the boundary between a word char (\w) and
                             # something that is not a word char
    

    Bonus Regex

    如果你今天感到沮丧,这种替代压缩(比原来的长吗?)应该让你振作起来。

    \b(?:a(?:(?:co|b)s|(?:cos|(?:si|ta)n)h|(?:si|ta)n))\b