[英]Regex to match string with exact number of identifier characters
Take the following paragraph:请看以下段落:
#### And this will not work!
This is an *italic*... does it work!
This is a **bold** text and it will work!
Will this ***work***
I have built this regex /(?:\\*{2}.*?\\*{2})/gm
to match words which start & end with **
characters.我已经构建了这个正则表达式/(?:\\*{2}.*?\\*{2})/gm
来匹配以**
字符开头和结尾的单词。 However, my regex also matches the last line Will this ***work***
, which I do not want it to.但是,我的正则表达式也匹配最后一行Will this ***work***
,这是我不希望的。
How can I set a restriction to watch for the next character after the match not to be another *
?如何设置限制以观察匹配后的下一个字符而不是另一个*
?
Thank you.谢谢你。
I suggest using我建议使用
string.match(/(?<!\*)\*{2}[^*]*\*{2}(?!\*)/g)
See the regex demo查看正则表达式演示
Pattern details图案详情
(?<!\\*)
- a negative lookbehind that fails the match if there is an asterisk immediately to the left of the current location (?<!\\*)
- 如果当前位置的左侧有一个星号,则匹配失败的负向后视\\*{2}
- double asterisk \\*{2}
- 双星号[^*]*
- zero or more chars other than an asterisk [^*]*
- 除星号外的零个或多个字符\\*{2}
- double asterisk \\*{2}
- 双星号(?!\\*)
- a negative lookahead that fails the match if there is an asterisk immediately to the right of the current location (?!\\*)
- 如果当前位置右侧有一个星号,则匹配失败的负前瞻JavaScript demo: 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));
You can use [^\\*]*
to match any number of characters that aren't an asterisk along with a negative look behind (?<!\\*)
which checks that the preceeding character isn't an asterisk and negative look ahead (?!\\*)
whcih checks that the following character isn't an asterisk:您可以使用[^\\*]*
来匹配任意数量的不是星号的字符以及后面的负向(?<!\\*)
以检查前面的字符不是星号和负向展望(?!\\*)
whcih 检查以下字符是否不是星号:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.