简体   繁体   中英

Finding numbers in regex (Javascript)

This is a weird question, but bear with me...

So, I'm messing around with RegEx: I have the following code and it works fine if the inputText var contains a comma, however If I change it to "99 x icecream, each £99" it does not work... (ie it alerts null)

var inputText ="99, icecream, each £99";  // expensive ice cream

var inputText = inputText.toString(); // this was done because I though if I started a string with a number js might do that weird conversion stuff it does, but I don't need it right?

var qXpe = inputText.match(/(\d{1,3})(,|[ x ]?) (\w+), each ([£]\d+[.]?\d{0,2})/g);

alert(qXpe);

I want to find sentences which are structured quantity, product, £price or quantity x product, £price , the current regex works for the former.

So this regex returns 99, icecream, each £99 but null for 99 x icecream, each £99

Can anyone hazard a guess as to why this does not work? Merci.

The number should be followed by a space when it's not followed by a comma but your regex doesn't reflect that, cause [ x ]? means either a space or an x, optionally. Maybe you want ( x )?

try:

(\d+)(?:, | x )(\w+), £(\d+)

you can use rubular to test your RegEx in real time. Enjoy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM