【问题标题】:Extract a number from a dynamic string [duplicate]从动态字符串中提取数字[重复]
【发布时间】:2020-11-12 01:39:12
【问题描述】:

字符串是动态的。示例

Date18:Month5:Year1984

我们怎样才能只提取数字 18。我不能使用子字符串,因为值是动态的。我只想提取日期之后和之前的数字:

【问题讨论】:

  • “我不能使用子字符串,因为值是动态的。”好吧,这显然是错误的:var str = "Date18:Month5:Year1984"; console.log(str.substring(4, str.indexOf(':')));
  • 基本正则表达式
  • 使用正则表达式。您可以使用this website 寻求帮助

标签: javascript node.js


【解决方案1】:

正则表达式非常适合匹配模式。有很多种写法,这里有几种写法。

var str = "Date18:Month5:Year1984"

const re = /^Date(\d+):Month(\d+):Year(\d+)$/;

const match = str.match(re);

console.log(match[1], match[2], match[3]);


const re2 = /(\d+)/g;

const match2 = str.match(re2);

console.log(match2[0], match2[1], match2[2]);

【讨论】:

    【解决方案2】:

    这是你想要的:

    const a = "Date18:Month5:Year1984";
    const match = a.match(/^Date([0-9]+?):/);
    
    if(match){
      console.log(match[1]);
    }

    【讨论】:

    • 它解决了我的问题。我对正则表达式不熟悉。它真的节省了我的时间。谢谢!
    猜你喜欢
    • 2018-12-14
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2018-06-11
    • 1970-01-01
    • 2012-06-15
    • 2018-08-30
    相关资源
    最近更新 更多