简体   繁体   中英

Regex to match decimal value

I have the following regex to match decimals:

@"[\d]{1,4}([.][\d]{1,2})?"

but I am able to input multiple decimal dots. How can I prevent this? In general, I can have input strings like "2000" or "2000.22". I have tried to use decimal.TryParse but I can input two decimal dots (eg 2000..)

Here is my class with method for validation:

 public static class ValidationUtils
 {
    public static bool IsValid(string text)
    {
        var regex = new Regex(@"^\d{1,9}([.]\d{1,2})?$");
        var success = regex.IsMatch(text);

        return success;
    }
 }

Here is the call in page's code-begind:

private void OnPreviewTextInput(object sender, TextCompositionEventArgs eventArgs)
{
    var box = eventArgs.OriginalSource as TextBox;
    if (box == null) return;
    eventArgs.Handled = !ValidationUtils.IsValid(box.Text + eventArgs.Text);
}

And the xaml of TextBox:

 <TextBox Text="{Binding Nominal, Mode=TwoWay,
 StringFormat={}{0:0.######}, UpdateSourceTrigger=PropertyChanged, 
 NotifyOnValidationError=True, ValidatesOnDataErrors=True,
 Converter={StaticResource  decimalValueConverter}}"
 PreviewTextInput="OnPreviewTextInput"/>

Am I use a wrong event here?

Thanks you.

You need to anchor your regex.

@"^\d{1,4}([.]\d{1,2})?$"

^ matches the start of the string

$ matches the end of the string

if you don't do that, you will get partial matches.

The issue is that your regex will match up to the last two numbers, if they are present and thus consider the string as a match. You need the anchors to tell the regex that the number should end with the last digits.

^\d{1,4}([.]\d{1,2})$

You don't need to put the square brackets around the \\d , and you can use \\. to escape the dot, like this:

^\d{1,4}(\.\d{1,2})$

You'll need to do a few things. First, you'll want to start with ^ and end with $ to make sure you don't have any unwanted beginning or ending characters. Next, you'll have to escape the . to make it a literal . As you already have noted, you'll want the ? after the grouping as the .## part is not required but allowed.

This makes your final regex the following:

@"^\d{1,4}(\.\d{1,2})?$";

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