2010-12-16 121 views
3

我需要一個正則表達式,它匹配一個數字(大於5,但小於500)和數字後面的文本字符串的組合。數字範圍和字符的正則表達式

例如,下面的比賽將返回true:6項或450個相關文件或300個資料Red(可以有單詞「文件」後其他字符)

而下面的字符串將返回false:4項或501項或40項紅

我試過以下的正則表達式,但它不工作:

string s = "Stock: 45 Items";   
Regex reg = new Regex("5|[1-4][0-9][0-9].Items"); 
MessageBox.Show(reg.IsMatch(s).ToString()); 

感謝您的幫助。

回答

5

此正則表達式應該用於檢查工作,如果數量是在範圍從5〜500:

"[6-9]|[1-9][0-9]|[1-4][0-9][0-9]|500" 

編輯:例如用更復雜的正則表達式,其中不包括數字1000太大,並且不包括其它字符串下面比「項目」之後的數字:

string s = "Stock: 4551 Items"; 
string s2 = "Stock: 451 Items"; 
string s3 = "Stock: 451 Red Items"; 
Regex reg = new Regex(@"[^0-9]([6-9]|[1-9][0-9]|[1-4][0-9][0-9]|500)[^0-9]Items"); 

Console.WriteLine(reg.IsMatch(s).ToString()); // false 
Console.WriteLine(reg.IsMatch(s2).ToString()); // true 
Console.WriteLine(reg.IsMatch(s3).ToString()); // false 
+1

第二部分匹配01,所以您需要更改第一個數字以禁止0. – unholysampler 2010-12-16 14:21:42

+0

@unholysampler:是的,您說得對,我已經編輯了正確的解決方案 – 2010-12-16 14:23:08

+1

感謝您的快速響應。不幸的是,你的正則表達式對於大於500的數字也返回true,我如何將字符串(Items)添加到正則表達式中? – Rob 2010-12-16 14:24:15

2

以下方法應該做你想做的。它使用的不止是正則表達式。但其意圖更爲明確。

// itemType should be the string `Items` in your example 
public static bool matches(string input, string itemType) { 
    // Matches "Stock: " followed by a number, followed by a space and then text 
    Regex r = new Regex("^Stock: (\d+) (.*)&"); 
    Match m = r.Match(s); 
    if (m.Success) { 
     // parse the number from the first match 
     int number = int.Parse(m.Groups[1]); 
     // if it is outside of our range, false 
     if (number < 5 | number > 500) return false; 
     // the last criteria is that the item type is correct 
     return m.Groups[2] == itemType; 
    } else return false; 
} 
+0

我必須同意這個答案,似乎是最合乎邏輯的情況。基本上從字符串中獲取數值,並進行數字比較。我沒有看到有一個清晰的正則表達式可以做到這一點,並且在編寫代碼時清晰度是一件好事! – onaclov2000 2010-12-16 14:30:10

+0

@onaclov,很高興你同意。謝謝。 – jjnguy 2010-12-16 14:35:36

0
(([1-4][0-9][0-9])|(([1-9][0-9])|([6-9])))\sItems 
0

什麼是「\ < 500> | \ < [1-9] [0-9] [0-9]> | \ < [1-9] [0-9]> | \ < [6-9]>「,它在linux shell中對我很好,所以它應該在c#中類似。他們在網上有一個bug,應該有反斜槓>在集合之後...例如500backslash> :-)

相關問題