Reputation: 181
If I have this string
If you eat 5 cookies you'll consume 200 calories
I need a regular expression which can extract 5 cookies
and 200 calories
In simple words I want a regular expression in java script which can extract numbers and word next to number
Upvotes: 0
Views: 3734
Reputation: 32785
If your text will always have the form If you eat <count_of> <something> you'll consume <some> calories
, the you can use the regex below
var regex = /^If you eat (\d+) (\w+) you'll consume (\d+) calories$/;
The second, third, and third matches will be the one that will interest you (the first match is the actual string).
If you want to capture the ( ) together instead of capturing into two separate matches, you can replace (\d+) (\w+)
by (\d+ \w+)
.
Upvotes: 0
Reputation: 388316
I think you can use
'If you eat 5 cookies you\'ll consume 200 calories'.match(/\d+(\.\d+)?\s\w+/g)
Demo: RegEx
Upvotes: 2