用于从字符串接收整数的C#模式创建

时间:2011-11-11 18:13:20

标签: c# pattern-matching

我有一些类似下面的字符串:

hu212 text = 1
reference = 1
racial construction = 1
2007 = 1
20th century history = 2

我想在'='之后只取整数...我怎么能这样做? 我正在尝试这个:

 Regex exp = new Regex(@"[a-zA-Z]*[0-9]*[=][0-9]+",RegexOptions.IgnoreCase);
            try
            {
                MatchCollection MatchList = exp.Matches(line);
                Match FirstMatch = MatchList[0];
                Console.WriteLine(FirstMatch.Value);
            }catch(ArgumentOutOfRangeException ex)
            {
                System.Console.WriteLine("ERROR");
            }

但它不起作用...... 我尝试了其他一些但我得到的结果如“20”或“hu212”...... 什么exaclty匹配呢?给我剩下的与reg不匹配的字符串?

5 个答案:

答案 0 :(得分:5)

而不是正则表达式,你也可以这样做:

int match = int.Parse(line.SubString(line.IndexOf('=')).Trim());

答案 1 :(得分:4)

您需要在\s和数字之间允许空格(=):

Regex pattern = new Regex(@"=\s*([0-9]+)$");

这是一个更完整的例子:

Regex pattern = new Regex(@"=\s*([0-9]+)$");
Match match = pattern.Match(input);
if (match.Success) 
{
    int value = int.Parse(match.Groups[1].Value);
    // Use the value
}

查看在线工作:ideone

答案 2 :(得分:1)

怎么样

string str = "hu212 text = 1"
string strSplit = str.split("=")[1].trim();

答案 3 :(得分:0)

String StringToParse = "hu212 text = 1";
String[] splitString = String.Split(StringToParse);

Int32 outNum;
Int32.TryParse ( splitString[splitString.Length-1], out outNum );

答案 4 :(得分:0)

 Regex pattern = new Regex(@"=\s?(\d)");

这允许有或没有空间。该号码在第1组中。

hu212 text =1
reference = 1