How to remove text in brackets using a regular expression

后端 未结 3 638
一生所求
一生所求 2020-12-18 20:44

I\'m looking for a regular expression which will perform the following:

INPUT: User Name (email@address.com)
OUTPUT: User Name

What would b

相关标签:
3条回答
  • 2020-12-18 21:07

    This should do the job:

    var input = "User Name (email@address.com)";
    var output = Regex.Replace(input, @" ?\(.*?\)", string.Empty);
    

    Note the escaping of the ( and ) chars so that they aren't recognised as group markers.

    0 讨论(0)
  • 2020-12-18 21:18

    Did you mean you want the user name output, rather than the email address? For either case, you don't need regexes. For example, assuming the input is always well-formed and hence leaving out any error checking,

    string output = input.Substring(0, input.IndexOf(" ("))
    

    will get you the user name. And if you did want the email address, that too is available without resorting to regexes:

    int n;
    string output = input.Substring(n = 1 + input.IndexOf('('),
                                    input.IndexOf(')') - n)
    
    0 讨论(0)
  • 2020-12-18 21:27

    I'm just offering another way to do this, although I would just use regex myself as this is clunky:

        string output = input.Split('(')[0].TrimEnd();
    
    0 讨论(0)
提交回复
热议问题