I'm writing a simple code in 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
. See the regex demo .
Details :
^
- start of string - (\\d+(?:,\\d{1,2})?)
- Capturing group 1 matching:
\\d+
- one or more digits (?:,\\d{1,2})?
- an optional sequence of:
,
- a comma \\d{1,2}
- 1 or 2 digits .*
- 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]+
In case you want to specify min max length use:
[0-9]{1,3}[, ]*[0-9]{0,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.