Home > Software design >  How to get string array from separate single string with multiple matching delimiter?
How to get string array from separate single string with multiple matching delimiter?

Time:07-31

I am trying to get the below output from this string in C#.

hi how are you? {Id} any string {Name} can come here {Test}

The output should be an array of the below strings:

Id Name Test

CodePudding user response:

You can try using regular expressions and Linq. Assuming that you have identfiers within {...} and each identifier must start from letter or _ and can contain letters, digits and _ you can put

using System.Linq;
using System.Text.RegularExpressions;

...

string text = "hi how are you? {Id} any string {Name} can come here {Test}";

var result = Regex
  .Matches(text, @"{[\p{L}_][\p{L}\d_]*}")
  .Cast<Match>()
  .Select(item => item.Value.Trim('{', '}'))
  .ToArray();

// Let's have a look:
Console.Write(string.Join(" ", result));

Output:

Id Name Test
  • Related