开发者

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 开发者_StackOverflow中文版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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜