简体   繁体   English

数字和数字旁边的单词的正则表达式javascript

[英]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 我需要一个可以提取5 cookies200 calories的正则表达式。简单来说,我想要一个Java脚本中的正则表达式,可以提取数字和数字旁边的单词。

I think you can use 我想你可以用

'If you eat 5 cookies you\'ll consume 200 calories'.match(/\d+(\.\d+)?\s\w+/g)
  • \\d+ - digits \\ d +-数字
  • \\s - a space after the digits \\ s-数字后的空格
  • \\w+ - some set of characters after the digits \\ w +-数字后的一组字符

Demo: RegEx 演示: 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 如果您的文本始终具有以下形式: If you eat <count_of> <something> you'll consume <some> calories ,则可以使用以下正则表达式

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+) . 如果要一起捕获()而不是捕获到两个单独的匹配项中,可以将(\\d+) (\\w+)替换为(\\d+ \\w+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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