我想知道如何在正则表达式中匹配除特定字符串(称为“for”
)之外的任何字符。
我在想也许是这样的:[^for]*
- 但那不起作用。
最佳答案
我确信这是一个骗局。
一种方法是通过如下所示的前瞻来开始您的模式:
(?=\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)
关于正则表达式说什么不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5929732/