2012-07-16 38 views
0

我有這個字符串我有一個字符串如何從字符串中提取數C#

"transform(23, 45)" 

提取23和45,我做

var xy = "transform(23,45)".Substring("transform(23,45)".indexOf('(') + 1).TrimEnd(')'); 
var num = xy.Split(','); 

我使用C#。有沒有更好的方法在c#中做到這一點?

回答

6

使用正則表達式:

string sInput = "transform(23, 45)"; 
Match match = Regex.Match(sInput, @"(\d)+", 
       RegexOptions.IgnoreCase); 

if (match.Success) 
{ 
    foreach (var sVal in match) 
      // Do something with sVal 
} 

你可以閱讀更多關於正則表達式here。 使用RegExr進行培訓,它可以幫助很多!

2

那麼,簡單的正則表達式字符串應該是([0-9]+),但是您可能需要定義其他表達式約束,例如,您在處理句點,逗號等字符串時做了什麼?

var matches = Regex.Matches("transform(23,45)", "([0-9]+)"); 
foreach (Match match in matches) 
{ 
    int value = int.Parse(match.Groups[1].Value); 
    // Do work. 
} 
+0

對於「句點,逗號等...」,並添加到列表中:非10位數字文字,強制類型文字([VB示例](http://msdn.microsoft.com/zh-cn/ com/en-us/library/s9cz43ek(v = vs.80).aspx),但其他編程語言也有它們)等等。 – 2012-07-16 06:44:18

0

這將做到這一點

string[] t = "transform(23, 45)".ToLower().Replace("transform(", string.Empty).Replace(")", string.Empty).Split(','); 
0

使用Regex

var matches = Regex.Matches(inputString, @"(\d+)"); 

解釋:

\d Matches any decimal digit. 

\d+ Matches digits (0-9) 
     (1 or more times, matching the most amount possible) 

和使用:

foreach (Match match in matches) 
{ 
    var number = match.Groups[1].Value; 
}