Regular expressions for a range of numbers and characters

I need a regular expression that matches a combination of a number (greater than 5, but less than 500) and the text string that comes after the number.

For example, the following matches will return true: 6 elements or 450 elements or 300 elements in red (there may be other characters after the word "elements")

While the following lines will return false: 4 elements or 501 elements or 40 red elements

I tried the following regular expression, but it does not work:

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

Thank you for your help.

+3
source share
4 answers

This regex should work to check if a number is in the range of 5 to 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
+5

, . , . .

// 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;
}
+2
(([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, #. , a > ... . 500backslash > : -)

0

Source: https://habr.com/ru/post/1780688/


All Articles