javascript - 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.
解决方案
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));
推荐阅读
- xamarin.ios - Xamarin.UITest:如何选择当前节点的下一个元素
- java - 添加/删除页面时,Android FragmentStatePagerAdapter 未正确更新 ViewPager
- security - Hacking & Seucrity : 订阅 CMS 和框架升级
- c# - 车速表指针旋转统一
- android - 无限滚动列表视图 - 在构建期间调用 setState() 或 markNeedsBuild
- java - 从 MainActivity 访问一个单独的进程
- angular - ng6:在 html 中动态形成变量名
- javascript - 对 flatList 中的项目进行排序
- django - Django inlineformset 如何不显示 id
- angular-material - mat-select disabled 没有从 angular5 的范围内拾取变量