Regular expression and commas

Hi, this works now, but I'm confused about why.

I am learning a regex and need to infer numbers from strings, e.g.

'Discount 7.5%' should get 7.5
'Discount 15%' should get 15
'Discount 10%' should get 10
'Discount 5%' should get 5

and etc.

/\d,?.\d?/ //works

/\d,?.\d,?/ //doesn't works

/\d?.\d?/ //doesn't works

I thought that one of the second two will work, can someone explain this.

+4
source share
4 answers

Fast and dirty with a clear regex.

//Let the system to optimize the number parsing for efficiency
parseFloat(text.replace(/^\D+/, ""));

Demo: http://jsfiddle.net/DerekL/4bnp8381/

+2
source

Try it. Make the second part with a dot .optional with?

(\d)*(\.\d*)?
0
source

Regex, , , , , lookbehind:

(?<=Discount\s)\d+(\.\d+)?

, PHP (prce). javascript.

EDIT: Javascript lookbehind, , JS Fiddle

var div = document.getElementById('test');
var text = div.innerHTML;
div.innerHTML = text.replace(/Discount (.*)%/ig,'$1');
<div id="test">
    Discount 7.5%<br>
    Discount 15%<br>
    discount 10%<br>
    Discount 5.433%<br>
    Fee 11%<br>
    Discount 22.7%
</div>
Hide result

, , , Fee 11%

0

, , :

^Discount\s(\d+(\.\d+)?)%$

Regex101

-1

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


All Articles