簡體   English   中英

用於從字符串接收整數的 C# 模式創建

[英]C# pattern creation for receiving an integer from a string

我有一些像下面這樣的字符串:

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");
            }

但它不起作用......我嘗試了其他一些但我得到了“20th”或“hu212”之類的結果......精確匹配有什么作用? 給我與 reg 不匹配的字符串的其余部分?

除了正則表達式,您還可以執行以下操作:

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

您需要在=和數字之間允許空格 ( \\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

關於什么

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

Int32 outNum;
Int32.TryParse ( splitString[splitString.Length-1], out outNum );
 Regex pattern = new Regex(@"=\s?(\d)");

這允許有或沒有空間。 該號碼在第 1 組中。

hu212 text =1
reference = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM