J B
J B

Reputation: 47

Regex replace by group in C#

I am trying to using regex replace in C# although I am having some issues getting the pattern to align correctly. What I am looking to do is replace certain combinations as per the first 2 groups but not if it matches the pattern of the 3rd group. What I have so far is

 var pattern = @"(,)|(\[\{)|(^:\[[*]])";

 string NewLineValue = Regex.Replace(LineValue, pattern,Environment.NewLine);

Essentially I want to replace all comma's or [{ combinations in a string but not if the comma appears within [[]] characters (e.g [[1234,5678]])

Any help is much appreciated...

Upvotes: 1

Views: 2028

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You need to match and capture all substrings between [[ and ]] (to be restored in the resulting string) and then match , or [{ in all other contexts to replace with a newline:

var pattern = @"(?s)(\[\[.*?]])|,|\[{";
var result = Regex.Replace(s, pattern, m => 
    m.Groups[1].Success ? m.Groups[1].Value : Environment.NewLine);

The pattern matches:

  • (?s) - a RegexOptions.Singleline inline option
  • (\[\[.*?]]) - Group 1: [[, any 0+ chars, as few as possible, and then ]]
  • | - or
  • , - a comma
  • | - or
  • \[{ - [{ substring.

If Group 1 matches (m.Groups[1].Success), the match is pasted back (m.Groups[1].Value), else, the match (, or [{) is replaced with a Environment.NewLine.

Upvotes: 4

Related Questions