【问题标题】:Regular Expressions for number range and characters数字范围和字符的正则表达式
【发布时间】:2010-12-16 14:13:16
【问题描述】:

我需要一个正则表达式来匹配数字(大于 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());

感谢您的帮助。

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    这个正则表达式应该用于检查数字是否在 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
    

    【讨论】:

    • 第二部分匹配01,所以你需要将第一个数字更改为不允许0。
    • @unholysampler:是的,你是对的,我已经编辑了正确的解决方案
    • 感谢您的快速回复。不幸的是,您的正则表达式对于数字 > 500 也返回 true,如何将字符串 (Items) 添加到正则表达式?
    • 在第一种情况下 [5-9] 也不允许 5 作为有效值吗?会不会是 [6-9] (因为值不大于 5)
    • 这正是我想要的。很棒的东西 - 非常感谢。
    【解决方案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;
    }
    

    【讨论】:

    • 我不得不同意这个答案似乎是最合乎逻辑的情况。基本上从字符串中获取值,并进行数值比较。我没有看到有明确的正则表达式可以做到这一点,在编写代码时,清晰是一件好事!
    • @onaclov,很高兴你同意。谢谢。
    【解决方案3】:
    (([1-4][0-9][0-9])|(([1-9][0-9])|([6-9])))\sItems
    

    【讨论】:

      【解决方案4】:

      那么 "\|\|\|\" ,它在 linux shell 中对我来说很好,所以它在 c# 中应该是相似的。他们在网络上有一个错误,在集合之后应该有反斜杠> ...例如500 反斜杠> :-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-18
        • 2019-06-22
        相关资源
        最近更新 更多