使用正则表达式检索不带字母数字的数字值

时间:2012-08-23 08:00:28

标签: c# regex

嗨,有人可以帮我从字符串中提取单独的数字。假设我的字符串如下

AB12(100).HJI(20).D76R(222)

我需要输出如下:

  100.20.222(I need to get the digits which are in brackets appended with dot)

5 个答案:

答案 0 :(得分:0)

确定。这很简单:

var value = @"AB12(100).HJI(20).D76R(222)"; 
MatchCollection matches = Regex.Matches(value, @"(?<=\()(\d+)(?=\))");  
var result = String.Join(matches, ".")

答案 1 :(得分:0)

另一种即兴创作:

string input = "AB12(100).HJI(20).D76R(222)";
string output = string.Join(".", Regex.Matches(input, @"\((?<value>\d{1,})\)").OfType<Match>().Select(m => m.Groups["value"].Value));

答案 2 :(得分:0)

var value = @"AB12(100).HJI(20).D76R(222)"; 
var matches = Regex.Matches(value, @"(?<=\()(\d+)(?=\))");
var result = String.Join(".", matches.OfType<Match>().Select(x => x.Value).ToArray());

答案 3 :(得分:0)

您还可以使用this替换正则表达式:

/[A-Za-z0-9]+\((\d+)\)/$1/g

C#代码为:

string input = "AB12(100).HJI(20).D76R(222)";
string pattern = @"[A-Za-z0-9]+\((\d+)\)";
string result = System.Text.RegularExpressions.Regex.Replace(input, pattern, "$1");

答案 4 :(得分:0)

只是另一个版本

 string text = "AB12(100).HJI(20).D76R(222)";
 MatchCollection match = Regex.Matches(text, @"\(\d+\)"); //(100)(20)(222)
 string[] digits = new string[match.Count];

 for(int i=0; i<digits.Length;i++)
 {
     digits[i] = match[i].Value.Trim(new char[]{'(',')'});
 }
 string output = String.Join(".", digits); //100.20.222