Home > Software design >  Splitting a string in Regex c#
Splitting a string in Regex c#

Time:10-30

I am trying to split a string in C# the following way:

The Input string is in the form

{ Items.Test1 } ~ { Items.test2 } - { Items.Test3 }

And I am trying to split it into an array of strings in the form

string[0]= "{ Items.Test1 }"
string[1]= " ~ "
string[2]=  "{ Items.test2 }"
string[3]= " - "
string[4]= "{ Items.Test3 }"

I was trying to do it in a way such as this

string[] result1 = Regex.Matches(par.Text.Trim(), @"\{(.*?)\}").Cast<Match>().Select(m => m.Value).ToArray();

It is not working correctly. Showing below results.

string[0]="{ Items.Test1 }"
string[1]="{ Items.test2 }"
string[2]="{ Items.Test3 }"

pls help me on this

CodePudding user response:

You need to use

Regex.Split(par.Text.Trim(), @"(\s [~-]\s )")

When splitting with a regex containing a capturing group, the captured texts are also output as part of the resulting array. See the enter image description here

See the C# demo:

var pattern = @"(\s [~-]\s )";
var text = "{ Items.Test1 } ~ { Items.test2 } - { Items.Test3 }";
var result = Regex.Split(text, pattern);
// To also remove any empty items if necessary:
//var result = Regex.Split(text, pattern).Where(x => !String.IsNullOrWhiteSpace(x)).ToList();
foreach (var s in result)
    Console.WriteLine(s);

Output:

{ Items.Test1 }
 ~ 
{ Items.test2 }
 - 
{ Items.Test3 }

CodePudding user response:

You can use this regex for matching:

[~-]|{[^}]*}

RegEx Demo

RegEx Details:

  • [~-]: Match a ~ or -
  • |: OR
  • {[^}]*}: Match a {...} substring

Code:

string pattern = @"[~-]|{[^}]*}";
string sentence = "{ Items.Test1 } ~ { Items.test2 } - { Items.Test3 }";
  
foreach (Match m in Regex.Matches(sentence, pattern))
   Console.WriteLine("Match '{0}' at position {1}", m.Value, m.Index);
  • Related