在解析用户输入的命令的一段代码中,我一直看到这个正则表达式模式:
const CopyPattern = /^COPY-((?!COPY-).)*$/;
const CutPattern = /^CUT-((?!CUT-).)*$/;
const PastePattern = /^PASTE-((?!PASTE-).)*$/;
...
为什么有人会用X
关注((?!X).)*
?
我的正则表达式技能可能会更强,一般来说,前瞻/后视是我还没有很好掌握的主题。这种模式有什么作用,它会匹配什么,为什么要使用 ^X-((?!X-).)*$
而不是 ^X-(.*)$
?
答案 0 :(得分:1)
采用以下模式:
^COPY-((?!COPY-).)*$
这个模式使用了一个回火点,表示匹配:
^ from the start of the input
COPY- the text "COPY-"
((?!COPY-).)* then match any single character provided that we can lookahead
and NOT cross the text "COPY-" again
$ end of the input
因此,缓和点通过使用负前瞻来确保我们匹配 .*
而不跨越某些内容,在本例中为文本 COPY-
。