RegEx matches comma separated numbers with optional decimal

I have a regular expression that matches comma-separated numbers with an optional two-digit decimal part in a given multi-line text.

/(?<=\s|^)\d{1,3}(,\d{3})*(\.\d{2})?(?=\s|$)/m

It matches strings of type 1, 12, 12.34, 12, 345.67, etc. How can I change it to fit a number with only a decimal part, for example .23?

EDIT: just to clarify - I would like to change the regex to match 12, 12.34and.34

And I'm looking for "independent" real numbers. that is, numerical lines whose boundaries are either spaces or the beginning / end of a line / line.

+4
source share
4 answers

It:

\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d

matches all of the following numbers:

1
12
.99
12.34 
12,345.67
999,999,999,999,999.99

If you want to exclude numbers, for example 123a(for example, street addresses) or 123.123(numbers with more than two digits after the decimal point), try:

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

A small demo (I assumed that you are using PHP):

$text = "666a 1 fd 12 dfsa .99 fds 12.34 dfs 12,345.67 er 666.666 er 999,999,999,999,999.99";
$number_regex = "/(?<=\s|^)(?:\d{1,3}(?:,\d{3})*(?:\.\d\d)?|\.\d\d)(?=\s|$)/";
if(preg_match_all($number_regex, $text, $matches)) {
  print_r($matches);
}

which will output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 12
            [2] => .99
            [3] => 12.34
            [4] => 12,345.67
            [5] => 999,999,999,999,999.99
        )

)

Note that it ignores lines 666aand666.666

+10
source
/(?<=\s|^)(\d{1,3}(,\d{3})*(\.\d{2})?|\.(\d{2}))(?=\s|$)/m

Or considering some countries where. used as the thousandth separator and used as the decimal separator.

/(?<=\s|^)(\d{1,3}(,\d{3})*(\.\d{2})?|\d{1,3}(\.\d{3})*(,\d{2})?|\.(\d{2})|,(\d{2}))(?=\s|$)/m

Insane Regex for internationalization

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

matches

14.23
14,23
114,114,114.23
114.114.114,23

Does not match

14.
114,114,114,23
114.114.144.23
,
.
<empty line>
+2
source

.

0

(@ "^ ((([0-9] +) (. ([0-9] +))?) (\ (([0-9] +) (. ([0-9] +))?)) *) $" )

, , , .

: : 1) 9,10 2) 10,1,11,12,15,15.2 3) 9,8 4) 9

: 1) 2..7 2) 2, 7 3) 2. 4) 7, 5), 6). 7).2 8), 2

-1

Source: https://habr.com/ru/post/1720072/


All Articles