我正在尝试匹配以下 Markdown 文本以进行强调:
_this should match_
__this shouldn't__
_ neither should this _
_nor this _
this _should match_as well_
__ (double underscore, shouldn't match)
我自己的努力以及其他解决方案面临的问题是它们最终仍然匹配第三行:
_ neither should this _
有办法检查我的特定用例吗?我的目标是浏览器应用程序,因为 Firefox and Safari are yet to support lookbehinds ,有没有一种方法可以在不使用后视的情况下做到这一点?
这是我迄今为止提出的正则表达式模式:/(_)((?!\1|\s).*)?\1/
幸运的是,我能够完成几乎所有的检查,但我的模式仍然匹配:
_nor this _
__ (double underscore, shouldn't match)
那么,有没有办法确保下划线之间至少有一个个字符,并且它们与文本之间不被空格分隔?
链接到正则表达式 Playground :regexr.com/5300j
示例:
const regex = /(_)((?!\1|\s).*)?\1/gm;
const str = `_this should match_
__this shouldn't__
_ neither should this _
_nor this _
this _should match_as well_
__
_ neither should this _`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
最佳答案
您可以使用其中任何一个
\b_(?![_\s])(.*?[^_\s])_\b
\b_(?![_\s])(.*?[^_\s])_(?!\S)
请参阅regex demo
详细信息
\b
- 比赛前不允许出现单词字符(字母、数字、_
)_
- 下划线(?![_\s])
-_
后不允许紧接着使用_
或空格字符(.*?[^_\s])
- 第 1 组:.*?
- 除换行符之外的任何 0 个或更多字符,尽可能少[^_\s]
- 除_
和空格之外的任何 1 个字符
_
- 下划线\b
-_
后面不允许有单词字符。
请注意,如果当前位置右侧没有非空白字符并充当右侧空白边界,则 (?!\S)
匹配失败。
关于javascript - 用于强调 Markdown 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61346949/