我想知道如何在正则表达式中匹配除特定字符串(称为"for"
)之外的任何字符。
我想也许是这样的:[^for]*
- 除了那不起作用。
答案 0 :(得分:3)
我确定这是一个重复。
一种方法是使用这样的先行开始你的模式:
(?=\A(?s:(?!for).)*\z)
在任何值得打扰的正则表达式系统中都可以这样写:
(?x) # turn /x mode on for commentary & spacing
(?= # lookahead assertion; hence nonconsumptive
\A # beginning of string
(?s: # begin atomic group for later quantification
# enable /s mode so dot can cross lines
(?! for ) # lookahead negation: ain't no "for" here
. # but there is any one single code point
) # end of "for"-negated anything-dot
* # repeat that group zero or more times, greedily
\z # until we reach the very end of the string
) # end of lookahead
现在只需将它放在你的模式的前面,然后添加你想要的其他内容。当你必须在模式中构建这样的知识时,这就是你表达逻辑!/for/ && ⋯
的方式。
当你必须把它放在一个模式中时,它与你构造/foo/ && /bar/ && /glarch/
的方式类似,这是
(?=\A(?s:.)*foo)(?=\A(?s:.)*bar)(?=\A(?s:.)*glarch)
答案 1 :(得分:2)
^(?!for$).*$
匹配除for
以外的任何字符串。
^(?!.*for).*$
匹配任何不包含 for
的字符串。
^(?!.*\bfor\b).*$
将任何不包含 for
的字符串作为完整单词匹配,但允许使用forceps
等字词。
答案 2 :(得分:0)
您可以尝试检查字符串是否与for
匹配,并以您使用的任何语言(例如Perl中的if (not $_ =~ m/for/)
)否定结果