Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - 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

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

But doesn't cover the perfectly the case with *

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

question from:https://stackoverflow.com/questions/65911084/regex-for-markdown-emphasis-with-asterisks-and-underscores

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use

/([_*])(?<!(?:1|w).)(?![_*s])(.*?[^_*s])(?=1)([_*])(?!w|3)/g

See the regex demo. Details:

  • ([_*]) - Group 1: _ or *
  • (?<!(?:1|w).) - a negative lookbehind: no same char as in Group 1 or any word char and then any char immediately to the left of the current location
  • (?![_*s]) - a negative lookahead that fails the match if there is _, * or whitespace immediately to the right of the current location
  • (.*?[^_*s]) - Group 2: any zero or more chars other than line break chars, as few as possible, and then a char other than _, * or whitespace
  • (?=1) - a positive lookahead that requires the same value as in Group 1 to be present immediately to the right of the current location
  • ([_*]) - Group 3: a _ or *
  • (?!w|3) - not immediately followed with a word char or same value as in Group 3.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...