简体   繁体   English

在正则表达式中查找数字(Javascript)

[英]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)所以,我在搞乱正则表达式:我有以下代码,如果 inputText var 包含逗号,它可以正常工作,但是如果我将它更改为“99 x 冰淇淋,每个 99 英镑”,它就不起作用......(即它警告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.我想找到结构化quantity, product, £pricequantity x product, £price的句子,当前的正则表达式适用于前者。

So this regex returns 99, icecream, each £99 but null for 99 x icecream, each £99所以这个正则表达式返回99, icecream, each £99null 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 ]?当数字后面没有逗号时,数字后面应该跟一个空格,但是您的正则表达式没有反映这一点,因为[ x ]? means either a space or an x, optionally.表示空格或 x,可选。 Maybe you want ( x )?也许你想要( x )?

try:尝试:

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

you can use rubular to test your RegEx in real time.您可以使用rubular实时测试您的 RegEx。 Enjoy享受

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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