Regex for Markdown Emphasis with asterisks * and underscores _

NOT A DUPLICATE OF Regex for Markdown Emphasis

but an upgrade.
The perfect regex posted into the answer covers only the case with underscores but Markdown support also asterisks.

TLTR: I need a regex to match markdown emphasis with _em_ and *em*

  • Not spaces before and after (_| *) both at beginning end ending of the match
  • Not double (_|*) at beginning at ending
  • No different start-end like *foo_

My attemp to solve the problem is

\b[_\*](?![_\*\s])(.*?[^_\*\s])[_\*]\b

But doesn’t cover the perfectly the case with *

Here is an example with some tests. Should match only the _em_ and *em* cases.

106 thoughts on “Regex for Markdown Emphasis with asterisks * and underscores _”