Skip to content
Advertisement

Regex Extraction – Mixed Decimal seperator

I am currently trying to write a regex in js that would extract the decimal numbers from a mixed string.

Example strings are following

mixed string123,456,00indeed
mixed string123,456.00indeed
mixed string123,4indeed
mixed string123,40indeed
mixed string 1,0
mixed string 1,00indeed
mixed string 1,00.00indeed

My desired output is following

123,456,00
123,456.00
123,4
123,40
1,0
1,00
1,00.00

If I run the following regex

(d+,)+(.)+(d+)

it doesnot return any match when the decimal point is followed by a single digit.Eg. following cases

mixed string123,4indeed
mixed string 1,0

I am not sure how to tune the regex that works for all such cases. If someone can please help me would be very helpful. The full js here

var str='mixed string123,4indeed';
str.match(/(d+,)+(.)+(d+)/gm);

Regex101screenshot

Also I am getting this in regex101 which I am not sure how to decipher

A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

Advertisement

Answer

You can use

/d+(?:,d+)*(?:.d+)?/g

See the regex demo.

Details:

  • d+ – one or more digits
  • (?:,d+)* – zero or more occurrences of a comma and one or more digits
  • (?:.d+)? – an optional occurrence of a dot and one or more digits.

See the JavaScript demo:

var texts = ['mixed string123,456,00indeed','mixed string123,456.00indeed','mixed string123,4indeed','mixed string123,40indeed','mixed string 1,0','mixed string 1,00indeed','mixed string 1,00.00indeed'];
var rx = /d+(?:,d+)*(?:.d+)?/g
for (var i=0; i<texts.length;i++) {
  console.log(texts[i], '->', (texts[i].match(rx) || ["No match!"])[0]);
}
Advertisement