开发者

Regex to match number or specific string (i.e. "all")

开发者 https://www.devze.com 2022-12-23 06:15 出处:网络
This sounds simple but my regex knowledge is limited. I need an expression to match a decimal number or the string \"all\", as in a range validato开发者_JAVA技巧r that allows the word all represent t

This sounds simple but my regex knowledge is limited.

I need an expression to match a decimal number or the string "all", as in a range validato开发者_JAVA技巧r that allows the word all represent the max range.

I thought something like this might work:

((^[-+]?\d*\.?\d*)|any)

But the above doesn't work for "any".


Here is a solution that does not make use of regex.

private static bool IsNumberOrGivenString(string number, string text, CultureInfo culture)
{
    double result;
    if (double.TryParse(number, NumberStyles.Float, culture, out result))
    {
        return true;
    }

    return number.Equals(text, StringComparison.OrdinalIgnoreCase);
}

private static bool IsNumberOrGivenString(string number, string text)
{
    return IsNumberOrGivenString(number, text, CultureInfo.InvariantCulture);
}

Sample use:

Console.WriteLine(IsNumberOrGivenString("898", "all")); // true
Console.WriteLine(IsNumberOrGivenString("all", "all")); // true
Console.WriteLine(IsNumberOrGivenString("whatever", "all")); // false
Console.WriteLine(IsNumberOrGivenString("898,0", "all", CultureInfo.GetCultureInfo("sv-SE"))); // true
Console.WriteLine(IsNumberOrGivenString("898,0", "all", CultureInfo.GetCultureInfo("en-US"))); // false

The upsides with this code over using a regex is that it (may) run in a localized manner, using whatever decimal sign that is used. It will also fail the number if it has, say a . in it, when that character is not a valid decimal separator.

Since the string comparison is ignoring case it will also match the word "all" regardless of whether it is "all", "All", "aLl" or any other combination of upper- and lowercase letters.


try this

(((-|\+)?\d+\.?\d*)|any)


With | the regex engine will likely check each possibility one by one, and return immediately if a match is found.

Since the subexpression

(^[-+]?\d*\.?\d*)

matches an empty string, the LHS of | will always succeed, thus the any part will always be ignored.

You should make this part not match an empty string, e.g.

(^[-+]?(?:\d+\.?\d*|\.\d+))
0

精彩评论

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