Home > Net >  Regex to extract string after a "|"
Regex to extract string after a "|"

Time:11-03

I am new to regex. I am trying to extract string post a "|". I have below type of string.

(String1) | (string2 string3)

I want to extract values of string2 and string3 using C#.

I have used below regex, however it didn't worked.

  1. @"*|(\S)"
  2. @"(?<=\|)(.*?)"

CodePudding user response:

With regex, you can use

var text = "(String1) | (string2 string3)";
var result = Regex.Match(text, @"\|\s*\(([^()]*)\)")?.Groups[1].Value;
Console.WriteLine(result); // => string2 string3

See also the regex demo. The \|\s*\(([^()]*)\) pattern matches a | char, then zero or more whitespaces, (, then captures into Group 1 any zero or more chars other than parentheses, and then matches a ) char.

Without regex, if the string is always like this, you may split with space | space, get the second item and trim out ( and ):

var result2 = text.Split(new[] {" | "}, StringSplitOptions.None)[1].Trim(new[] {'(', ')'});
Console.WriteLine(result2); // => string2 string3

See the C# demo.

CodePudding user response:

This can help you. Use Split() method, which return an array and take the second element [1].

  public string ExtractString(string str)
    {
        return str.Split("|")[1].Trim('(',')');
    }

Have a good day :)

  • Related