【问题标题】:Regex to capture whole word with specific beginning正则表达式以特定开头捕获整个单词
【发布时间】:2012-10-24 00:20:04
【问题描述】:

我需要捕获一个作为附加整数传递给 CSS 类的数字。我的正则表达式很弱,我想做的很简单。我认为“负词边界”\B 是我想要的标志,但我想我错了

string = "foo bar-15";
var theInteger = string.replace('/bar\-\B', ''); // expected result = 15

【问题讨论】:

    标签: javascript jquery regex syntax


    【解决方案1】:

    使用here 概述的捕获组:

    var str= "foo bar-15";
    var regex = /bar-(\d+)/;
    var theInteger = str.match(regex) ? str.match(regex)[1] : null;
    

    然后你可以在任何你需要使用它的地方做一个if (theInteger)

    【讨论】:

    • 这里的问题是,如果没有尾随数字,match 返回null 并且尝试访问null[1] 会抛出错误。最好先致电match,然后再进一步检查结果(见我的回答)。
    • 更漂亮的是theInteger = str.match(regex) ? RegExp.$1 : null
    • @SeanKinsey——让我们变得愚蠢。如果null 是一个OK 结果,那么theInteger = str.match(regex) && RegExp.$1; 是最漂亮的(到目前为止)。
    • @RobG,当然我只是讨厌将 && 运算符用作条件运算符。
    • 嘿,Crockford 说"guard" 没问题,所以这给了我carte blance,不是吗? ;-)
    【解决方案2】:

    试试这个:

    var theInteger = string.match(/\d+/g).join('')
    

    【讨论】:

    • Nah - 我想在未来防止其他基于整数的类被引入 CSS。匹配“bar-”字符并删除它们以获得整数是必要的。
    【解决方案3】:
    string = "foo bar-15";
    var theInteger = /bar-(\d+)/.exec(string)[1]
    theInteger // = 15
    

    【讨论】:

      【解决方案4】:

      如果你只想要末尾的数字(一种反向 parseInt),为什么不呢:

      var num = 'foo bar-15'.replace(/.*\D+(\d+)$/,'$1');
      

      var m = 'foo bar-15'.match(/\d+$/);
      var num = m? m[0] : '';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-12
        相关资源
        最近更新 更多