4

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?

1
  • 1
    It turns out I had to remove the /g, I changed it to /i. Thank you everyone anyway. Can someone please remove this question as I am not registered. Commented Jul 10, 2011 at 0:03

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to switch to using exec. The match function that they were using also returns the array of matches.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.