【问题标题】:Regex to match number after string without the matching string正则表达式在没有匹配字符串的情况下匹配字符串后的数字
【发布时间】:2018-05-04 13:33:27
【问题描述】:

我正在尝试在 javascript 中编写一个正则表达式来匹配特定字符串之后的一系列数字,而不会得到结果中的字符串。到目前为止,我想出了这个:

(?!smart_id=)[0-9]+

将针对以下字符串进行测试:

ksld8403smart_id=9034&kqwop
discid=783&smartid=83234&ansqw
fdsjfnfd3209sdf&smart_id=2102&hjg

但我得到了 smart_id 前后的数字。测试需要在https://regexr.com/上进行

【问题讨论】:

  • 这看起来像一个查询参数字符串。使用库函数或内置语言函数来提取这些值会更容易且不易出错。
  • Lookbehind 目前还不是 JS RegExp 中的标准功能,我的 Chrome 控制台中的/(?<=smart_id=)[0-9]+/.exec("smart_id=232134")[0] 显示为"232134",但要使其与其他浏览器和版本兼容,您需要使用@987654327 @。因此,在 regexr 中,您将永远无法丢弃左侧匹配的一部分(除非它支持新的 JS 正则表达式语法)。

标签: javascript regex


【解决方案1】:

您可以将正则表达式与array#map 一起使用。匹配结果后,您可以array#split= 上的结果并获取第一个索引处的值。

var str = `ksld8403smart_id=9034&kqwop
discid=783&smartid=83234&ansqw
fdsjfnfd3209sdf&smart_id=2102&hjg`;

console.log(str.match(/(smart_id=)(\d+)/g).map(matched => +matched.split('=')[1]));

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2012-06-05
    • 2013-12-25
    相关资源
    最近更新 更多