简体   繁体   English

正则表达式匹配数字,最多2位小数

[英]Regular Expression that matches number with max 2 decimal places

I'm writing a simple code in java/android. 我在java / android中编写一个简单的代码。

I want to create regex that matches: 我想创建匹配的正则表达式:

0
123
123,1
123,44

and slice everything after second digit after comma. 并在逗号后的第二个数字后切片。

My first idea is to do something like that: 我的第一个想法是做那样的事情:

^\d+(?(?=\,{1}$)|\,\d{1,2})

 ^ - from begin
 \d+ match all digits
 ?=\,{1}$ and if you get comma at the end
 do nothin
 else grab two more digits after comma

but it doesn't match numbers without comma; 但它不匹配没有逗号的数字; and I don't understand what is wrong with the regex. 我不明白正则表达式有什么问题。

You may use 你可以用

^(\d+(?:,\d{1,2})?).*

and replace with $1 . 并以$1替换。 See the regex demo . 请参阅正则表达式演示

Details : 细节

  • ^ - start of string - (\\d+(?:,\\d{1,2})?) - Capturing group 1 matching: ^ - 字符串的开头 - (\\d+(?:,\\d{1,2})?) - 捕获第1组匹配:
    • \\d+ - one or more digits \\d+ - 一个或多个数字
    • (?:,\\d{1,2})? - an optional sequence of: - 可选序列:
      • , - a comma , - 一个逗号
      • \\d{1,2} - 1 or 2 digits \\d{1,2} - 1或2位数
  • .* - the rest of the line that is matched and not captured, and thus will be removed. .* - 匹配且未捕获的其余行,因此将被删除。

Here: 这里:

,{1}

says: exactly ONE "," 说:一个“,”

Try: 尝试:

,{0,1}

for example. 例如。

basic regex : [0-9]+[, ]*[0-9]+ 基本正则表达式: [0-9]+[, ]*[0-9]+

In case you want to specify min max length use: 如果您想指定最小最大长度使用:

[0-9]{1,3}[, ]*[0-9]{0,2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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