在解析用户输入命令的代码部分,我一直看到以下regex模式:
const CopyPattern = /^COPY-((?!COPY-).)*$/;
const CutPattern = /^CUT-((?!CUT-).)*$/;
const PastePattern = /^PASTE-((?!PASTE-).)*$/;
...
为什么有人会用((?!X).)*
来追随X
?
我的正则表达式技能可能会更强,通常我还不太了解前瞻性/后向性。这种模式做什么,它会匹配什么,为什么要使用^X-((?!X-).)*$
而不是^X-(.*)$
?
采用以下模式:
^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-
。