EMM
EMM

Reputation: 181

Regular expression for number and word next to number javascript

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

Answers (2)

Cristik
Cristik

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

Arun P Johny
Arun P Johny

Reputation: 388316

I think you can use

'If you eat 5 cookies you\'ll consume 200 calories'.match(/\d+(\.\d+)?\s\w+/g)
  • \d+ - digits
  • \s - a space after the digits
  • \w+ - some set of characters after the digits

Demo: RegEx

Upvotes: 2

Related Questions