Home > Mobile >  C# Split a string by a regular expression including regular expressions as separate substrings
C# Split a string by a regular expression including regular expressions as separate substrings

Time:11-09

I'm trying to make a string that will appear character by character on a screen. I made it running, but now I'm facing the issue that when the string has color tags or any other tag, the tag is also written character by character applying its effect only when the tag closes. I was thinking of separating those tags as regex, so I could just put them immediately to make them work properly. for that, I need to do the following.

I have my string

string myText = "I'm sorry, you don't have enough <color=#00FF00>energy</color> to continue";

Usually when I apply the regex I get

  • "I'm sorry, you don't have enough"
  • "energy"
  • "to continue"

What I need is the following

  • "I'm sorry, you don't have enough"
  • "<color=#00FF00>"
  • "energy"
  • "</color>"
  • "to continue"

I need to have the tags in the string array separated from the inner strings. Is there a way to make it possible?

Thanks in advance

I tried using Regex.Split:

Regex.Split(myText, @"<.*?>");

but I cannot match the regular expression to keep the tags as separated substrings inside the string array

CodePudding user response:

Try this:

string myText = @"I'm sorry, you don't have enough <color=#00FF00>energy</color> to continue";

string[] split = Regex.Split(myText, @"(<[^>] >)");
foreach (string s in split)
{
    Console.WriteLine(s);
}

Console.ReadLine();
  •  Tags:  
  • c#
  • Related