【问题标题】:What does this negative lookahead regex pattern mean?这种负前瞻正则表达式模式是什么意思?
【发布时间】:2021-08-02 08:31:15
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您是否尝试过使用regex101.com
  • ((?!COPY-).)* 通常被称为 tempered 点,将匹配与 .* 相同的内容,但 没有 跨越文本 @987654329 @.
  • @WaisKamal 是的,它解释了它将匹配的内容,但没有解释为什么
  • @TimBiegeleisen 只是使用“tempered”这个词给了我一些谷歌的东西,所以谢谢你!介意将其扩展为答案吗?
  • @WantonBarnacles -- 我支持 regex101 推荐!如果您花任何时间使用 Regex,这是天赐之物,绝对值得收藏! ??????

标签: javascript regex regex-lookarounds regex-negation


【解决方案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-

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多