首页 > 解决方案 > 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. However, my regex also matches the last line Will this ***work***, which I do not want it to.

How can I set a restriction to watch for the next character after the match not to be another *?

Thank you.

标签: javascriptregexmatch

解决方案


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
  • [^*]* - zero or more chars other than an asterisk
  • \*{2} - double asterisk
  • (?!\*) - a negative lookahead that fails the match if there is an asterisk immediately to the right of the current location

JavaScript demo:

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));


推荐阅读