簡體   English   中英

正則表達式匹配十進制值

[英]Regex to match decimal value

我有以下正則表達式匹配小數:

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

但我可以輸入多個小數點。 我怎么能阻止這個? 一般來說,我可以輸入字符串,如“2000”或“2000.22”。 我試過使用decimal.TryParse,但我可以輸入兩個小數點(例如2000 ..)

這是我的類,包含驗證方法:

 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;
    }
 }

這是頁面代碼中的調用 - 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);
}

和TextBox的xaml:

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

我在這里使用了錯誤的活動嗎?

謝謝。

你需要錨定你的正則表達式。

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

^匹配字符串的開頭

$匹配字符串的結尾

如果你不這樣做,你將獲得部分匹配。

問題是你的正則表達式將匹配最后兩個數字,如果它們存在,那么將字符串視為匹配。 你需要錨點告訴正則表達式,數字應該以最后的數字結束。

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

您不需要在\\d周圍放置方括號,也可以使用\\. 逃避點,像這樣:

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

你需要做一些事情。 首先,您需要以^開頭並以$結尾,以確保您沒有任何不需要的開頭或結尾字符。 接下來,你將不得不逃避。 使它成為文字。 正如你已經注意到的,你會想要的嗎? 分組后,#。部分不是必需的,但允許。

這使您的最終正則表達式如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM