开发者

Regular Expressions for number range and characters

开发者 https://www.devze.com 2023-01-30 17:47 出处:网络
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.

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.

For example, the following matches would return true: 6 Items or 450 Items or 300 Items Red (t开发者_如何学JAVAhere can be other characters after the word "Items")

Whereas the following strings would return false: 4 Items or 501 Items or 40 Red Items

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:

"[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:

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#. they have a bug here on web, there should be backslash> after the sets ... e.g. 500backslash> :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消