Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

actionscript - RegEx to match comma separated numbers with optional decimal part

I've a regex that matches comma separated numbers with an optional two digit decimal part in a given multiline text.

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

It matches strings like 1, 12, 12.34, 12,345.67 etc successfully. How can I modify it to match a number with only the decimal part like .23?

EDIT: Just to clarify - I would like to modify the regex so that it matches 12, 12.34 and .34

And I am looking for 'stand alone' valid numbers. i.e., number-strings whose boundaries are either white space or start/end of line/string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This:

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

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 like 123a (street addresses for example), or 123.123 (numbers with more than 2 digits after the decimal point), try:

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

A little demo (I guessed you're 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})*(?:.dd)?|.dd)(?=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 the strings 666a and 666.666


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...