这种负前瞻正则表达式模式是什么意思?

时间:2021-05-12 00:14:07

标签: javascript regex regex-lookarounds regex-negation

在解析用户输入的命令的一段代码中,我一直看到这个正则表达式模式:

const CopyPattern = /^COPY-((?!COPY-).)*$/;
const CutPattern = /^CUT-((?!CUT-).)*$/;
const PastePattern = /^PASTE-((?!PASTE-).)*$/;
...

为什么有人会用X关注((?!X).)*

我的正则表达式技能可能会更强,一般来说,前瞻/后视是我还没有很好掌握的主题。这种模式有什么作用,它会匹配什么,为什么要使用 ^X-((?!X-).)*$ 而不是 ^X-(.*)$

1 个答案:

答案 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-