heyumar
heyumar

Reputation: 51

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... (i.e. 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.

Upvotes: 0

Views: 158

Answers (2)

varzan
varzan

Reputation: 587

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 )?

Upvotes: 1

Artem
Artem

Reputation: 261

try:

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

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

Upvotes: 0

Related Questions