【问题标题】:Regular expression for number and word next to number javascript数字javascript旁边的数字和单词的正则表达式
【发布时间】:2015-05-14 04:43:42
【问题描述】:

如果我有这个字符串

If you eat 5 cookies you'll consume 200 calories

我需要一个可以提取5 cookies200 calories 的正则表达式 简而言之,我想要一个 java 脚本中的正则表达式,它可以提取数字旁边的数字和单词

【问题讨论】:

    标签: javascript regex numbers words


    【解决方案1】:

    我认为你可以使用

    'If you eat 5 cookies you\'ll consume 200 calories'.match(/\d+(\.\d+)?\s\w+/g)
    
    • \d+ - 数字
    • \s - 数字后的空格
    • \w+ - 数字后面的一些字符集

    演示:RegEx

    【讨论】:

    • 谢谢你..!但我想对数字使用这个正则表达式 var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm" );
    【解决方案2】:

    如果您的文本始终采用If you eat <count_of> <something> you'll consume <some> calories 形式,您可以使用下面的正则表达式

    var regex = /^If you eat (\d+) (\w+) you'll consume (\d+) calories$/;
    

    第二个、第三个和第三个匹配项将是您感兴趣的匹配项(第一个匹配项是实际字符串)。

    如果您想将 ( ) 捕获在一起而不是捕获到两个单独的匹配项中,您可以将 (\d+) (\w+) 替换为 (\d+ \w+)

    【讨论】:

    • 谢谢你..!但是我必须对数字使用这个正则表达式 var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm" );文本也不总是这种形式
    • I have to sue this regular expressionI'm allowed to use only thisThis better suits my needs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2011-05-12
    相关资源
    最近更新 更多