Question

Here is the pattern on which i'm Working :

/^\d+((.\d+))?(,\d+((.\d+))?)*$/

Its supports

1.2,30.5,13.54

25.65

But i want the pattern which supports following:

1.3,.3,4.5

.3,.4,.6

.2

1.3,5.6,.5

Was it helpful?

Solution

Based on your given examples, you require a decimal part, so you could use

/(\d*\.\d+),?/

This will match every given example. In case you also want to match numbers without a decimal dot, just add a second match:

/(\d*\.\d+|\d+),?/

Oh, and for JavaScript, to add the "g" modifier (for global search), you need to add it as a second parameter to the RegExp constructor:

re = new RegExp("(\d*\.\d+|\d+),?", "g");

Example: http://regex101.com/r/vL5aT0

Okay, I don't know on what purpose you are matching your strings. If you just want to validate them and they should exactly look like in your examples, use this:

/((\d*\.\d+|\d+),?)*(\d*\.\d+|\d+)$/

Thanks to Elergy for pointing me to this. By the way, Elergy's regex also matches useless lines of only periods and commas, like

.3,.4,.5,,,,8,.,7.,.,.,.,4.,.,.,.,.9,.,,,4.,,1,,

OTHER TIPS

/(\d+)?\.\d+(,?)/

(\d+)? Match all digits but optional.
\d+(,?) Match all digits with a , as optional.

If my understanding of your problem is right, this expression can help you:

/^\d*[\.,]\d*(?:,\d*[\.,]\d*)*$/

What do you want to do with them afterwards? If you goal is to identify a comma separated list of valid floating point numbers, you can use the Number constructor, which returns NaN if the number is invalid (which evaluates to false):

"1.3,5.6,a.s".split(",").every(Number)
false
"1.3,5.6,.5".split(",").every(Number)
true

Personally I like to avoid regex where possible and I think that this is pretty self-documenting. split the string on , and check that every value is a valid number.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top