合并多个 REGEX 语句
我有一个示例字符串。
This should be **bold**, *indented* or ***bold and indented***.
该字符串使用 3 个正则表达式进行解析,这些正则表达式依次运行以获得以下结果:
This should be <b>bold</b>, <i>indented</i> or <b><i>bold and indented</i></b>.
它很简单并且工作正常。但是,我想节省几行(如果可能、更漂亮、更高效,那为什么不呢?),然后合并它们。在单个正则表达式语句中进行所有替换。是否可以提高效率?或者我应该保持原样? (即使应该,我也想看到一个可能的解决方案?)
我的匹配语句:
\*\*\*(.+?)\*\*\*
->$1
\*\*(.+?)\*\*
->$1
\*(.+?)\*
->$1
I have an example string.
This should be **bold**, *indented* or ***bold and indented***.
The string is parsed using 3 regex that run one after another to get the following result:
This should be <b>bold</b>, <i>indented</i> or <b><i>bold and indented</i></b>.
It's simple and works fine. However, I'd like to save me a few lines (if it's possible, prettier, and more efficient, then why not eh?), and merge them. To make all the replacements in a single regex statement. Is it possible with extra efficiency? or should I leave it as is? (even if I should, I'd like to see a possible solution?)
My matching statements:
\*\*\*(.+?)\*\*\*
-><b><i>$1</b></i>
\*\*(.+?)\*\*
-><b>$1</b>
\*(.+?)\*
-><i>$1</i>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
老实说,将它们保留为 3 个独立的正则表达式几乎可以肯定...
行数越少并不总是越好,尤其是在正则表达式方面。
此外,您实际上只需要 2 个正则表达式 - 粗体和斜体。始终先运行粗体:
在粗体正则表达式之后运行...
然后斜体正则表达式使得...
这是正确的输出。 (首先运行粗体的原因是因为斜体会将
***
匹配为*
这是错误的。)Honestly, keeping them as 3 separate regexes is almost certainly...
Fewer lines is not always better, especially when it comes to regexes.
Also, you only actually need 2 regexes - the bold one and the italic one. Just always run the bold one first:
becomes, after the bold regex...
and then the italic regex makes that...
Which is the correct output. (The reason for running the bold one first is because the italic one would match
***
as<i>*</i>
which is wrong.)