S Kirchner
S Kirchner

Reputation: 123

RegularExpressions in WPF

I know there are already some kind of posts, that try to explain the RegEx-string. but i still don't get it. In my case, I need a regex for a WPF, that only allows "Numeric-Keyboard". Its here in the Code:

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
  Regex regex = new Regex("[-+]?[0-9]*,?[0-9]*");
  e.Handled = regex.IsMatch(e.Text);
}

so here are some example-numbers, i need to allow: "1" or "-1" or "-0,5" or "4,00" or "-3,56" or "3,3" or

" '-2, ' as '-2,0' or '-2' "

(so its all between -4 to +4. There can be a comma, But it don't have to be. If there s a comma, it needs one or 2 digits behind - not more. It should also be a "," not a "." - this is important) Does anybody know how to write this RegEx-String? thanks

Upvotes: 0

Views: 167

Answers (3)

JohnyL
JohnyL

Reputation: 7132

string s = "-3,5;10;8.5;0;2;3.5;1,5";
string pattern = @"^-?[0-4](,\d{1,2})?$";
foreach(var num in s.Split(";"))
{
    Console.WriteLine($"Num: {num}, Matches: {Regex.IsMatch(num, pattern)}");
}

Upvotes: 0

npinti
npinti

Reputation: 52185

Breaking it down, what you are after is not that complicated.

First off, your maximum/minimum range is from -4 up till 4. Taking into consideration the decimal section, you can have the following: ^[+-]?4(,0{1,2})?$. So in here, we expect a + or a - (optionally), the number 4, optionally followed by a comma and one or two 0's.

In your case, we now need to match the middle of your range, that is, from -3.99 up till 3.99. This can be achieved as follows: ^[+-]?[0-3](,\d{1,2})?$. In this case, we are also expecting a + or a - (optionally). We then expect to match a digit, between 0 and 3, optionally followed by a comma and 1 or 2 digits.

Combining them, we end up with something like so: ^[+-]?((4(,0{1,2})?)|([0-3](,\d{1,2})?))$. Example available here.

EDIT: As per the comments, you need to escape the slash in front of the \d, because the C# compiler will try and find a special meaning for \d, just like it does when you do \n, or \t. The easiest way is to use the @ character, so that the C# compiler threats the string as a literal: Regex regex = new Regex(@"^[+-]?((4(,0{1,2})?)|([0-3](,\d{1,2})?))$");.

Upvotes: 1

Peregrine
Peregrine

Reputation: 4546

There are a number of online sites for testing regular expressions, that will break down the match string and provide an explanation for each element, e.g. https://regex101.com/

In your case, you need

optional '+' or '-'
either
    a group consisting of 
        '4' 
        optionally followed by a group consisting of 
            ',' and one or two '0'
or 
    a group consisting of  
        one character from '0' .. '3'   
        optionally followed by a group consisting of 
            ',' and one or two characters from '0' to '9'


[+-]?(?:(?:4(?:,0{1,2})?)|(?:[0-3](?:,[0-9]{1,2})?))

Upvotes: 0

Related Questions