【问题标题】:regex to get the number from the end of a string正则表达式从字符串末尾获取数字
【发布时间】:2018-06-18 06:20:53
【问题描述】:

我有一个类似 stringNumber 的 id 变量,如下所示:example12 我需要一些 javascript 正则表达式来从字符串中提取 12。“example”对于所有 id 都是恒定的,只是数字会有所不同。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    这个正则表达式匹配字符串末尾的数字。

    var matches = str.match(/\d+$/);
    

    如果成功,它将返回一个 Array 及其 0th 元素匹配。否则,它将返回null

    在访问0 成员之前,请确保匹配成功。

    if (matches) {
        number = matches[0];
    }
    

    jsFiddle.

    如果一定要Number,可以用函数来转换,比如parseInt()

    number = parseInt(number, 10);
    

    【讨论】:

    • 提示:使用[0-9] 比使用\d 更有效。见stackoverflow.com/questions/16621738
    • @Marathon55 很可能是这样,但我自己还是会使用\d(除非它成为性能瓶颈)
    【解决方案2】:

    正则表达式:

    var str = "example12";
    parseInt(str.match(/\d+$/)[0], 10);
    

    字符串操作:

    var str = "example12",
        prefix = "example";
    parseInt(str.substring(prefix.length), 10);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-23
      • 2011-02-25
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多