【问题标题】:Regex to match string with exact number of identifier characters正则表达式匹配字符串与标识符字符的确切数量
【发布时间】:2020-12-17 05:42:07
【问题描述】:

取以下段落:

#### And this will not work!
This is an *italic*... does it work!
This is a **bold** text and it will work!
Will this ***work***

我已经构建了这个正则表达式 /(?:\*{2}.*?\*{2})/gm 来匹配以 ** 字符开头和结尾的单词。但是,我的正则表达式也匹配最后一行 Will this ***work***,这是我不希望的。

如何设置限制以在匹配后监视下一个字符而不是另一个 *

谢谢。

【问题讨论】:

  • /(?<!\*)\*{2}[^*]*\*{2}(?!\*)/g?见regex101.com/r/UGJQxP/1
  • 谢谢@WiktorStribiżew,这对我有用。如果您可以将其发布为答案,我会接受。干杯。
  • @WiktorStribiżew 您应该开始将您的解决方案作为答案发布,因为它们就是答案。

标签: javascript regex match


【解决方案1】:

我建议使用

string.match(/(?<!\*)\*{2}[^*]*\*{2}(?!\*)/g)

regex demo

模式详情

  • (?&lt;!\*) - 如果当前位置的左侧有一个星号,则匹配失败
  • \*{2} - 双星号
  • [^*]* - 零个或多个除星号以外的字符
  • \*{2} - 双星号
  • (?!\*) - 如果当前位置右侧有一个星号,则匹配失败

JavaScript 演示:

const string = "#### And this will not work!\nThis is an *italic*... does it work!\nThis is a **bold** text and it will work!\nWill this ***work***";
console.log(string.match(/(?<!\*)\*{2}[^*]*\*{2}(?!\*)/g));

【讨论】:

    【解决方案2】:

    您可以使用[^\*]* 匹配任意数量的不是星号的字符以及(?&lt;!\*) 后面的否定查看,以检查前面的字符不是星号和否定查看(?!\*) 进行检查以下字符不是星号:

    const str = `#### And this will not work!
    This is an *italic*... does it work!
    This is a **bold** text and it will work!
    Will this ***work***`
    
    console.log(str.match(/(?<!\*)\*{2}[^\*]*\*{2}(?!\*)/g))

    【讨论】:

    • @Kayote 因为它是从我的评论中复制的解决方案,所以只是 * 在字符类中被不必要地转义了。
    猜你喜欢
    • 2022-11-13
    • 2019-03-22
    • 2020-08-22
    • 2013-01-13
    • 2016-07-12
    • 2022-01-17
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多