2010-12-16 64 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> :-)

相关问题