2012-04-11 22 views
-6

我需要找到正則表達式的幫助不大適合我的需要,我想是可以輸入任意的字符串,正則表達式找到任何和所有的整數值,並返回他們,說數字的正則表達式?

string s1 = "This is some string" 
string s2 = " this is 2 string" 
string s3 = " this is 03 string" 
string s4 = "4 this is the 4th string" 
string s5 = "some random string: sakdflajdf;la 989230" 
string s6 = "3494309 [email protected]# 234234" 

現在我要的是正則表達式返回,

for s1 = return null (// nothing) 
s2 = return 2 
s3 = return 0 and 3 (// may separately as 0 and 3 or together as 03 doesn't matter) 
s4 = return 4 and 4 (// it has 4 2 times right?) 
s5 = 989230 (// may together as this or separately as 9 8 9 2 3 0 again is unimportant, but what's important is that it should return all integer values) 
s6 = 3494309 and 234234 (// again may they be together as this or like this 3 4 9 4 3 0 9 and 2 3 4 2 3 4 that is unimportant, all that is imp is that it should return all integers) 

我已經試過[0-9]\d^.*[0-9]+.*$,但他們都不似乎工作。任何人都可以幫忙嗎?

PS:請參閱Rename file using regular expression

+5

你是如何應用表達式的?請發佈您的代碼。也請澄清你的意思*,但他們似乎沒有工作*。什麼不工作?你得到的結果是什麼? '\ d'只匹配一個數字,'^。* [0-9] +。* $'匹配整個字符串,如果它至少包含一個數字。看來你想要'\ d +'。 – 2012-04-11 20:02:51

+0

下面的答案會在您的輸入中找到數字。您可以編寫一個方法,返回給定數字的值。我建議使用switch語句。 – jac 2012-04-11 20:10:28

+0

請查看[鏈接]上的更新問題(http://stackoverflow.com/questions/10117237/rename-file-using-regular-expression) – Razort4x 2012-04-12 04:10:41

回答

8

正則表達式的更新問題,將陸續匹配一個或多個數字是:

\d+ 

您可以應用這樣說:

Regex.Matches(myString, @"\d+") 

這將返回一個MatchCollection對象的集合。這將包含匹配的值。

你可以使用它像這樣:

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

if (matches.Count == 0) 
    return null; 

var nums = new List<int>(); 
foreach(var match in matches) 
{ 
    nums.Add(int.Parse(match.Value)); 
} 

return nums; 
+0

先生,你甚至讀過我的整個問題嗎? – Razort4x 2012-04-11 20:03:18

+0

爲了讓它們全部分開,只需使用'\ d'。 – Servy 2012-04-11 20:03:22

+0

@ Razort4x:問題是你的問題中沒有很多信息,所以我們只能猜測。 – 2012-04-11 20:04:10

2

我知道這似乎有點淺顯的,但我認爲\d會做你想要什麼

我知道你說你想這...一件事要小心的是,如果你使用字符串來表示這個,你需要忽略轉義

var pattern = @"\d+";