4

Hi this is working now but I am confused at to why.

I am learning regex and need to pull the numbers out of strings like

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

etc.

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

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

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

I thought one of the second two would work could someone explain this.

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
Thomas K
  • 65
  • 5
  • 1
    **1.** You should escape the dots `.` in all three regex by preceding it with \, **2.** Use `\d+` to match more than one digits **3.** No need of `,` in any regex – Tushar Nov 05 '15 at 04:36
  • Define "does not work". – RobG Nov 05 '15 at 04:37
  • Possible duplicate of [regular expression for DOT](http://stackoverflow.com/questions/3862479/regular-expression-for-dot) – Basilevs Nov 05 '15 at 04:39
  • IMO, use [`(\d+(\.\d+)?)`](https://regex101.com/r/iL3dR1/1) with first capture group – Tushar Nov 05 '15 at 04:42

4 Answers4

2

Quick and dirty with easy to understand regex.

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

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

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

Try this. Make the second part with dot . optional with ?

(\d)*(\.\d*)?
Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
0

IF you check this Regex, this is what you need so it will return the float number only if the word before it is Discount by making use of the lookbehind operator:

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

But the problem is that works with PHP(prce) I can't get it working with javascript.

EDIT: As mentioned in here regex and commas Javascript does not support lookbehind regex so here is what I did to work around it 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>

As you see it does match it only if it was followedd by the word Discount, the word Fee 11% does not match

Community
  • 1
  • 1
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
  • @TimBiegeleisen, I'm sorry but it is not the same – Mi-Creativity Nov 05 '15 at 05:29
  • My inputs are pretty standard but I do like that this checks for the word Discount. I tried starting using replace but in something like this i could not get it to work. var re = /\d,?.\d?/; var vipextract = re.exec(cusvipdis); var skuextract = re.exec(skutext); – Thomas K Nov 05 '15 at 21:16
-1

You can use the following regex, which will match one or more digits, optionally followed by a decimal point and any number of digits:

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

Regex101

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360