简体   繁体   中英

How to remove text in brackets using a regular expression

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

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

What would be the best way to achieve this? Using regular expression to extract the text within the brackets and replacing this and any )( characters?

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.

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)

我只是提供了另一种方法来执行此操作,尽管我自己会使用正则表达式,因为这很笨拙:

    string output = input.Split('(')[0].TrimEnd();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM