SomeBruh
SomeBruh

Reputation: 460

How to specify regex replacement for different capturing groups in F#

I'm writing a md2html compiler in F# and I want to replace the ** surrounding texts with <b> and </b> tags.

e.g. this is **bold** will be changed to this is <b>bold</b>

I am trying to accomplish this with Regex.Replace method using the pattern (\*\*).*?(\*\*). So the first capturing group will be replaced by <b> and the second one will be replaced by </b> I would like to know how I can specify the replacement for these different "capturing groups" rather than the entire regex match?

Upvotes: 6

Views: 1139

Answers (3)

Ethan
Ethan

Reputation: 4375

Just use this regex: \*\*(.*?)\*\* and replace the matches with <b>$1</b>

Explanation:

  • \*\* matches ** literally.
  • ( starts a capture group.
  • .* just matches everything it can get that isn't a new line.
  • ? this makes the .* lazy, so that it doesn't match other bold text.
  • ) ends the capture group.
  • \*\* matches ** literally.

Upvotes: 5

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

The simplest way to do this is to capture the inner group instead of the surrounding ** and then use it in the replacement.

Regex.Replace("this is **bold**", "\*\*(.*?)\*\*", "<b>$1</b>")

Regex.Replace doesn't replace captured groups, but the whole match.

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627128

You should capture what you need to keep. You need to just match what you need to replace.

Use \*\*(.*?)\*\* pattern and <b>$1</b> replacement.

If you expect line breaks in between asterisks, use a singleline modifier (?s): (?s)\*\*(.*?)\*\*

Upvotes: 4

Related Questions