开发者

Getting separate parts of a regex in javascript match [duplicate]

This question already has answers here: How do you access the matched groups in a JavaScript regular expression? (24 answers) Closed 6 years ago.

I have the following regex in javascript. I want to match a string so its product (,|x) quantity, each price. The following regex does this; however it returns an array with one element only. I want an array which returns the whole matched string first followed by product, quantity, each price.

// product,| [x] quantity, each price:
var pQe = inputText.match(/(^[a-zA-z -]+)(?:,|[ x ]?) (\d{0,3}), (?:each) ([£]\d+[.]?\d{0,2})/g);

(,|x) means followed by a comma or x, so it will match ice-cream, 99, $开发者_运维知识库99 or ice-cream x 99, $99

How can I do that?


Use the exec function of the RegExp object. For that, you'll have to change the syntax to the following:

 var pQe = /(^[a-z ... {0,2})/g.exec(inputText)

Element 1 of the returned array will contain the first element of the match, element 2 will contain the second, and so on. If the string doesn't match the regular expression, it returns null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜