Regex a decimal number with comma

时光总嘲笑我的痴心妄想 提交于 2019-12-04 08:05:13

This is a very long and convoluted regular expression that fits all your requirements. It will work if your regex engine is based on PCRE (hopefully you're using PHP, Delphi or R..).

(?<=[^\d,.]|^)\d{1,3}(,(\d{3}))*((?=[,.](\s|$))|(\.\d+)?(?=[^\d,.]|$))

DEMO on RegExr

The things that make it so long:

  1. Matching multiple numbers on the same line separated by only 1 character (a space) whilst not allowing partial matchs requires a lookahead and a lookbehind.
  2. Matching numbers ending with . and , without including the . or , in the match requires another lookahead.

(?=[,.](\s|$)) Explanation

When writing this explanation I realised the \s needs to be a (\s|$) to match 1, at the very end of a string.

This part of the regex is for matching the 1 in 1, or the 1,000 in 1,000. so let's say our number is 1,000. (with the . on the end).

Up to this point the regex has matched 1,000, then it can't find another , to repeat the thousands group so it moves on to our (?=[,.](\s|$))

(?=....) means its a lookahead, that means from where we have matched up to, look at whats coming but don't add it to the match.

So It checks if there is a , or a . and if there is, it checks that it's immediately followed by whitespace or the end of input. In this case it is, so it'd leave the match as 1,000

Had the lookahead not matched, it would have moved on to trying to match decimal places.

This works for all the ones that you have listed

^[0-9]{1,3}(,[0-9]{3})*(([\\.,]{1}[0-9]*)|())$

. means "any character". To use a literal ., escape it like this: \..

As far as I know, that's the only thing missing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!