简体   繁体   中英

TextBox filter using Regex

I am struggling to apply a filter on a TexBox. I have 3 filter types:

1) Only Numbers (positive) Example: 123 good, -123, ad8, 12.0 not good

2) Only Numbers plus "^" and "." chars Only Numbers plus "^" and "." chars Example: 123^3, -34, -34.5 good, ad8, 23-4 not good

3) Only POSITIVE Numbers plus "^" and "." chars Only POSITIVE Numbers plus "^" and "." chars Example: 123^3, 34.5 good, -34, ad8, 23-4 not good

Here is my work:

private void PriceInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox tb = sender as TextBox;

            switch (FieldType)
            {
                case InputFieldType.TypeQuantity:
                    tb.Text = KeyFilter.ExtractNumbersOnly(tb.Text);
                    break;
                case InputFieldType.TypePositivePrice:
                    tb.Text = KeyFilter.ExtractPositivePricesOnly(tb.Text);
                    break;
                case InputFieldType.TypePrice:
                    tb.Text = KeyFilter.ExtractPricesOnly(tb.Text);
                    break;
            }
        }

and KeyFilter:

public static string ExtractNumbersOnly(string s)
{
    Match match = System.Text.RegularExpressions.Regex.Match(s, "\\d+");

    return match.Value;
}

public static string ExtractPricesOnly(string s)
{
    Match match = System.Text.RegularExpressions.Regex.Match(s, "^[-]?\\d+([.]\\d+)?$");

    return match.Value;
}

public static string ExtractPositivePricesOnly(string s)
{
    Match match = System.Text.RegularExpressions.Regex.Match(s, "^[+]?\\d+([.]\\d+)?$");

    return match.Value;
}

(1)

^\\d+$

(2)

^-?\\d+(\\.\\d+)?(\\^)?(-?\\d+(\\.\\d+)?)?$

(3) actually easier than (2). Just take (2) and remove the negative signs.

^\\d+(\\.\\d+)?(\\^\\d+(\\.\\d+)?)?$

The required three regex are sequentially(as you asked) at below:

^\\d+$

^-?\\d+[.^]\\d+$

^\\d+[.^]\\d+$

Please escape the \\ with your escape character in C#

Regex.IsMatch("123", "^\\d+$")
Regex.IsMatch("-123^33", "^-?\\d+((\\^\\d+)|(\\.\\d+))?$")
Regex.IsMatch("123^33", "^\\d+((\\^\\d+)|(\\.\\d+))?$")

Note that 2nd and 3rd does NOT work if ^ and . both are included, eg 123.44^2 <- as per given RegEx, this is NOT a correct input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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