Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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?

like image 660
SomeBruh Avatar asked Jun 03 '17 15:06

SomeBruh


People also ask

How do I reference a capture group in regex?

If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .

How do I capture two groups in regex?

They are created by placing the characters to be grouped inside a set of parentheses ( , ) . We can specify as many groups as we wish. Each sub-pattern inside a pair of parentheses will be captured as a group. Capturing groups are numbered by counting their opening parentheses from left to right.

How do you substitute in regex?

To perform a substitution, you use the Replace method of the Regex class, instead of the Match method that we've seen in earlier articles. This method is similar to Match, except that it includes an extra string parameter to receive the replacement value.

How do I reference a capture group in regex python?

Normally, within a pattern, you create a back-reference to the content a capture group previously matched by using a backslash followed by the group number—for instance \1 for Group 1. (The syntax for replacements can vary.)


1 Answers

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.
like image 161
Ethan Avatar answered Sep 29 '22 02:09

Ethan