[Solved] Getting the substring after a character in C# using regex


In C#, use Substring() with IndexOf:

string val = val.Substring(val.IndexOf(']') + 1);

enter image description here

If you have multiple ] symbols, and you want to get all the string after the last one, use LastIndexOf:

string val = "[01/02/70]\nhello [01/02/80] world ";
string val = val.Substring(val.LastIndexOf(']') + 1); // => " world "

If you are a fan of Regex, you might want to use a Regex.Replace like

string val = "[01/02/70]\nhello [01/02/80] world ";
val = Regex.Replace(val, @"^.*\]", string.Empty, RegexOptions.Singleline); // => " world "

See demo

Notes on REGEX:

  • RegexOptions.Singleline makes . match a linebreak
  • ^ – matches beginning of string
  • .* – matches 0 or more characters but as many as possible (greedy matching)
  • \] – matches literal ] (as it is a special regex metacharacter, it must be escaped).

7

solved Getting the substring after a character in C# using regex