wyc
wyc

Reputation: 55293

How to modify this regex so it doesn't match * * *

(?<!\*)\*([^*]+?)\*(?!\*)/g

This is basically a regex to match Markdown italics. It will match the following situations:

This *is* Markdown.
This *is Markdown.*
*This* is *Markdown.*
*This is Markdown.*

Note: The negatives lookarounds are there to avoid matching cases like this one This is **Markdown.**

It works ... almost. It's also matching * * *, which I use as section breaks. Like this:

* * *

This *is* Markdown.

* * *

How to change my regex so it doesn't match these section breaks? I'm really stuck.

RegExr: https://regexr.com/4tv5n

Upvotes: 1

Views: 99

Answers (2)

Diadistis
Diadistis

Reputation: 12174

According to the documentation there are more valid horizontal rule combinations.

This one I think is simpler and better captures the essence of the rule :

\*(?!\s*\*)([^*\n]+)\*

It is also faster, as it takes 89 steps instead of 204 steps.

Upvotes: 2

Eraklon
Eraklon

Reputation: 4288

This may suffice (?<!\*)\*([^ ][^*]*?)\*(?!\*). For the example at least.

Upvotes: 1

Related Questions