我对正则表达式很糟糕,但是我已经试过了一个谷歌(甚至看过reddit的来源)而且我仍然卡住了,所以这里:
我的目标是匹配以下"代码"并将其替换为HTML标记.这只是我坚持的正则表达式.
**bold text**
_italic text_
~hyperlink~
Run Code Online (Sandbox Code Playgroud)
这是我对大胆的尝试:
^\*\*([.^\*]+)\*\*$
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?我正在使用preg语法.
使用:
\*\*(.[^*]*)\*\*
Run Code Online (Sandbox Code Playgroud)
解释:
\*\* // match two *'s
(. // match any character
[^*] // that is not a *
*) // continuation of any character
\*\* // match two *'s
Run Code Online (Sandbox Code Playgroud)
在字符类“[ ]”中,“^”仅当它是第一个字符时才有意义。so(.*)匹配任何内容,(.[^*]*)匹配任何内容直到文字 *
编辑:为了响应在 (ie **bold *text**) 中匹配星号的注释,您必须使用非贪婪匹配:
\*\*(.*?)\*\*
Run Code Online (Sandbox Code Playgroud)
字符类是更有效的非贪婪匹配,但不可能在字符类内进行分组(请参阅“括号和反向引用...”)