数字范围和字符的正则表达式

我需要一个正则表达式,它匹配数字(大于5,但小于500)和数字后面的文本字符串的组合。

例如,以下匹配将返回true:6个项目或450个项目或300个项目红色(“项目”一词后面可能有其他字符)

以下字符串将返回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到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 

以下方法应该做你想要的。 它使用的不仅仅是正则表达式。 但其意图更加明确。

 // 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; } 
 (([1-4][0-9][0-9])|(([1-9][0-9])|([6-9])))\sItems 

怎么样“\ <500> | \ <[1-9] [0-9] [0-9]> | \ <[1-9] [0-9]> | \ <[[6-9]>” ,它在linux shell中对我很好,所以它应该在c#中类似。 他们在网上有一个bug,应该有套牌后反斜杠>例如500backslash> 🙂