0

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.

3
  • 1
    Could we see what results you get out of your current regex, and what you want to get out? Commented Jul 8, 2011 at 23:40
  • I want to find sentences which are structured quantity, product, £price or quantity x product, £price, the current regex works for the former. Commented Jul 8, 2011 at 23:41
  • Edited so it explains it better. Commented Jul 8, 2011 at 23:44

2 Answers 2

1

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

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

1 Comment

Thank you, you were correct! I've added a space character after the number (\d{1,3}\s?) ...etc, it seems to work now
0

try:

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

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

6 Comments

Can I ask, what does the : mean in this context?
the ?: is a lookahead prefix that doesn't capture the , or the x like (, | x ) would. So that your returned structure only has the useful parts you want/need. So the captured items are: [1] quantity, [2] product, [3] price
I write with it a lot to ensure structure in the input text. So once you start getting longer strings to parse, you eventually want to separat your data in some way with special characters, and this helps in certain cases. Look at ruby-doc.org/docs/ProgrammingRuby/html/language.html#UJ for regex rules
That looks like a non-capturing group to me.
right. got it confused with the zero-width positive lookahead for a sec. Still serves its purpose.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.