I am currently trying to write a regex in js that would extract the decimal numbers from a mixed string.
Example strings are following
JavaScript
x
8
1
mixed string123,456,00indeed
2
mixed string123,456.00indeed
3
mixed string123,4indeed
4
mixed string123,40indeed
5
mixed string 1,0
6
mixed string 1,00indeed
7
mixed string 1,00.00indeed
8
My desired output is following
JavaScript
1
8
1
123,456,00
2
123,456.00
3
123,4
4
123,40
5
1,0
6
1,00
7
1,00.00
8
If I run the following regex
JavaScript
1
2
1
(d+,)+(.)+(d+)
2
it doesnot return any match when the decimal point is followed by a single digit.Eg. following cases
JavaScript
1
3
1
mixed string123,4indeed
2
mixed string 1,0
3
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
JavaScript
1
3
1
var str='mixed string123,4indeed';
2
str.match(/(d+,)+(.)+(d+)/gm);
3
Also I am getting this in regex101 which I am not sure how to decipher
JavaScript
1
2
1
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
2
Advertisement
Answer
You can use
JavaScript
1
2
1
/d+(?:,d+)*(?:.d+)?/g
2
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:
JavaScript
1
5
1
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'];
2
var rx = /d+(?:,d+)*(?:.d+)?/g
3
for (var i=0; i<texts.length;i++) {
4
console.log(texts[i], '->', (texts[i].match(rx) || ["No match!"])[0]);
5
}