如何创建正则表达式以匹配不同的单词?
我尝试了以下正则表达式,但它也匹配其他单词中嵌入的单词:
@"(abs|acos|acosh|asin|asinh|atan|atanh)"
例如,使用
@"xxxabs abs"
abs
本身应匹配,但不在xxxabs
内。
答案 0 :(得分:1)
虽然解决方案(单词边界)是一个古老的经典,但你的问题很有趣,因为交替中的单词非常相似。
你可以从这开始:
\b(?:abs|acos|acosh|asin|asinh|atan|atanh)\b
压缩到那个:
\b(?:a(?:cosh?|sinh?|tanh?|bs))\b
它是如何运作的?
\b
来确保匹配不会嵌入更大的单词中。<强>令牌通过令牌强>
\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