简体   繁体   中英

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

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

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+) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM