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>
2
  • Please include the 3 regexes you are using. Commented Oct 4, 2011 at 16:28
  • I genuinely think it should be quite obvious (this is no noob question) I'll add it nonetheless. Commented Oct 4, 2011 at 16:30

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Noted, still though, for theoretic studies, can you make a working example?
Not really, because basic regex doesn't allow logic in its replacements (e.g. you can't say "replace with this string in these conditions, or that string in those conditions"). Some languages have callback-based regex replacement, which could do it, but you'd have to specify a language first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.