简体   繁体   English

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

[英]Regular Expressions for number range and characters

I need a regular expression that matches a combination of a number (larger than 5, but smaller than 500) and a text string that comes after the number. 我需要一个正则表达式,它匹配数字(大于5,但小于500)和数字后面的文本字符串的组合。

For example, the following matches would return true: 6 Items or 450 Items or 300 Items Red (there can be other characters after the word "Items") 例如,以下匹配将返回true:6个项目或450个项目或300个项目红色(“项目”一词后面可能有其他字符)

Whereas the following strings would return false: 4 Items or 501 Items or 40 Red Items 以下字符串将返回false:4个项目或501个项目或40个红色项目

I tried the following regex, but it doesn't work: 我尝试了以下正则表达式,但它不起作用:

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

Thanks for your help. 谢谢你的帮助。

This regex should work for checking if number is in range from 5 to 500: 这个正则表达式应该用于检查数字是否在5到500的范围内:

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

Edit : below example with more complex regex, which excludes numbers greater than 1000 too, and excludes strings other than " Items" after a number: 编辑 :下面的示例包含更复杂的正则表达式,它也会排除大于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

The following method should do what you want. 以下方法应该做你想要的。 It uses more than regular expressions. 它使用的不仅仅是正则表达式。 But its intent is more clear. 但其意图更清晰。

// 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

What about "\\<500>|\\<[1-9][0-9][0-9]>|\\<[1-9][0-9]>|\\<[6-9]>" , it works for me fine in linux shell so it should be similar in c#. 怎么样“\\ <500> | \\ <[1-9] [0-9] [0-9]> | \\ <[1-9] [0-9]> | \\ <[[6-9]>” ,它在linux shell中对我很好,所以它应该在c#中类似。 they have a bug here on web, there should be backslash> after the sets ... eg 500backslash> :-) 他们在网上有一个bug,应该有套牌后面的反斜杠>例如500backslash> :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM