[英]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. 有人可以帮我写一个正则表达式,格式为
(x), (x)
,其中x
可以是任何一位数字。 I am able to write match a format like (x)
as follows: 我可以编写匹配
(x)
的格式,如下所示:
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. 如果您不需要捕获非数字,那么对于数字,仅实际需要的模式是
\\d
。
Each match of \\d
will be the individual number found as the parser works across the string. \\d
每个匹配项都是解析器跨字符串工作时发现的单个数字。
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
The example you gave has RegexOptions.IgnoreCase
. 您提供的示例具有
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.
考虑到文化,因此“ a”还与“À”,“Ô和“Ä”等相关,它们也必须进行处理。
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? 如果您不相信我,请查看Jeff Atwood(Stackoverflow的联合创始人)对regex不区分大小写的答案是否更慢?
Are you looking for something like this? 您是否正在寻找这样的东西?
\(([0-9])\),\s?\([0-9]\)
Also, when trying to write Regexps, I would recommend using Regex101.com . 另外,在尝试编写Regexps时,我建议使用Regex101.com 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.