【发布时间】:2021-01-26 23:48:06
【问题描述】:
比如说我有这样的文字:
hello world **ant*** lorem **cat** opposum** *** ***antelope*** *rabbit __dog__
我想匹配只有 ** 和 __ 作为其前面和结束字符的字符串。所以在上面的例子中,我只想匹配“cat”和“dog”。这意味着如果周围有多余的字符,我必须取消或否定匹配。例如,***dog** 或 __dog___ 应该会失败。
我试图用消极的目光环顾 http://www.regular-expressions.info/lookaround.html 来解决这个问题,但无济于事。
这是我目前的模式
const pattern = /([^*])\*(\w+)\*([^*])/g;
const match = pattern.exec(text);
const annotatedText = match[0];
const matchedText = match[1];
// Return if annotatedText is a possible match for bolditalic
if (annotatedText.startsWith("***") || annotatedText.startsWith("___")) {
return;
}
// Return if the matchedText has spaces in between
if (/\s/.test(matchedText)) {
return;
}
if (text.match(/^([*_ \n]+)$/g)) {
return;
}
在 javascript 正则表达式中,
基本上,我想删除 javascript 字符串检查并在正则表达式模式本身上添加逻辑。
【问题讨论】:
标签: regex regex-lookarounds regex-negation