简体   繁体   中英

Regex to match format of (x), (x)

Can somebody help me to write a regex for format like (x), (x) where x can be any single digit number. I am able to write match a format like (x) as follows:

Regex rgx = new Regex(@"^\(([^)]+\)$", RegexOptions.IgnoreCase)

If you don't need to capture the non numbers, then only pattern actually required is \\d for a numeric.

Each match of \\d will be the individual number found as the parser works across the string.

For example:

var values = Regex.Matches("(1) (2)", @"\d")
                  .OfType<Match>()
                  .Select (mt => mt.ToString())
                  .ToArray();

Console.WriteLine ("Numbers found: {0}", string.Join(", ", values));
// Writes out->
// Numbers found: 1, 2

Eratta

The example you gave has RegexOptions.IgnoreCase . This actually does slow down pattern matching because the parser has to convert any character to its neutral counterpart of either upper or lower case before it compares to the words in the target match. Culture is taken into account so 'a' is also connected with 'À', 'Ã', and 'Ä' etc which too have to be processed.

Since you are dealing with numbers using that option makes no sense.

If you don't believe me, look at Jeff Atwood's (Stackoverflow's co-founder) answer to Is regex case insensitivity slower?

Are you looking for something like this?

\(([0-9])\),\s?\([0-9]\)

Also, when trying to write Regexps, I would recommend using Regex101.com .

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