簡體   English   中英

匹配文本開頭的浮點數-正則表達式

[英]Match float number at the beginning of a text -Regular Expression

我想匹配這些示例,格式為#。###,##

有效的例子

455,80SomeText
1,00
30,82
7,78 SomeText
622,21
8.542,85

無效的例子

455,482
54,1
7454,50

我已經嘗試過: ^[0-9]+(\\,[0-9][0-9])

更新1

  • 數字格式#。###,##
  • 數字后可以包含一些文本

您不需要在正則表達式中完全考慮千位分隔符...

^[0-9]{0,3}(?:\.[0-9]{3})*,[0-9]{2}(?![0-9])

regex101演示

如果您也不想接受,42 ,請使用:

^[0-9]{1,3}(?:\.[0-9]{3})*,[0-9]{2}(?![0-9])

regex101演示

(?:\\.[0-9]{3})*允許成千上萬。

逗號不需要轉義,並且(?![0-9]) (負前瞻)是為了防止數字后跟更多數字。

試試這個正則表達式:

^\-?\d{1,3}(\.\d\d\d)*(,\d+)?

細分:

^           # drop anchor at the start of the line. Then...
\-?         # match an optional negative sign, followed by...
\d{1,3}     # match 1-3 decimal digits, followed by...
(           # a group, consisting of
  \.        # * a thousands separator, followed by
  \d\d\d    # * 3 decimal digits 
)*          # with the group repeated zero or more times, followed by...
(           # a group, consisting of
  ,         # * a decimal point, followed by
  \d+       # * 1 or more decimal digits
)?          # with the group being optional

您應注意,千位分隔符和小數點是特定於區域性的。 此外,並非所有文化都以3為一組的數字。

為了使這種跨文化的可移植性,您需要實例化一個合適的System.Globalization.CultureInfo ,向下鑽取其NumberFormatInfo屬性,並使用該文化的數字組成規則動態構建正則表達式。

我不確定您要查找的格式是什么,但是聽起來您可以在RegEx中使用重復限定符,例如^[0-9]+(,[0-9]{2})我認為表達式中存在問題是您要轉義不是正則表達式特殊字符的逗號。

這是有關RegEx的很好的參考: http : //www.regular-expressions.info/repeat.html

暫無
暫無

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

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