开发者

Merge multiple REGEX statements

开发者 https://www.devze.com 2023-04-10 08:36 出处:网络
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:

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>


Honestly, keeping them as 3 separate regexes is almost certainly...

  1. More readable
  2. Simpler
  3. (Due to #1 and #2) More maintainable.

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:

***foo***

becomes, after the bold regex...

*<b>foo</b>*

and then the italic regex makes that...

<i><b>foo</b></i>

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号