javascript - 允许负号nodeJS表达式吗?

标签 javascript regex

目前我正在传递 URL 参数,例如 h-3678/q-55/con-0.11 但由于我的最新开发,我需要能够在 内传递减号con 参数如下:h-3678/q-55/con--0.5/ 但它使用我现在得到的表达式抛出错误?

let con_match = str.match(/(con-[^\\]+?)(?=\/)/);
let con = 0;
if (con_match && con_match.length) {
    con = con_match.shift().split('-').pop();
}

最佳答案

如果您的号码总是出现在con-之后,您可以使用

let strs = ["h-3678/q-55/con-0.11", "h-3678/q-55/con--0.5/"];
for (let i=0; i < strs.length; i++) {
  let str = strs[i];
  console.log(str);
  let con_match = str.match(/\bcon-(-?\d+(?:\.\d+)?)/);
  let con = 0;
  if (con_match) {
    con = con_match[1]; 
  }
  console.log("Result:", con);
}

正则表达式详细信息

  • \b - 单词边界(\b 单词边界仅在不属于另一个单词时才匹配 con,前面也没有数字或 _)
  • con- - 文字子字符串
  • (-?\d+(?:\.\d+)?) - 第 1 组(con_match[1] 值):
    • -? - 可选连字符
    • \d+ - 1+ 位数字
    • (?:\.\d+)? - 出现 1 或 0 次 .,然后出现 1+ 位数字

假设con和最后一个数字之间可能有任何文本,您可以提取与/\b匹配的con (con-[^\/]+)/ 正则表达式,然后在获得第 1 组值后,从其末尾提取数字:

let strs = ["h-3678/q-55/con-0.11", "h-3678/q-55/con--0.5/"];
for (let i=0; i < strs.length; i++) {
  let str = strs[i];
  console.log(str);
  let con_match = str.match(/\b(con-[^\/]+)/);
  let con = 0;
  if (con_match) {
    let m = con_match[1].match(/-(-?\d+(?:\.\d+)?)$/)
    if (m) { 
      con = m[1]; 
    }
  }
  console.log("Result:", con);
}

第二个正则表达式是 /-(-?\d+(?:\.\d+)?)$/:

  • - - 连字符
  • (-?\d+(?:\.\d+)?) - 第 1 组:
    • -? - 可选连字符
    • \d+ - 1+ 位数字
    • (?:\.\d+)? - 出现 1 或 0 次 .,然后出现 1+ 位数字
  • $ - 字符串结尾。

关于javascript - 允许负号nodeJS表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54808767/

相关文章:

javascript - 如何调试外部评估脚本

javascript - Node.js + MongoDB 不提交 upsert,为什么?

javascript - 用于缓存 JSON 的共享首选项与 SQLite

javascript - html2canvas z-index 无效

java - string.split() 和处理重复项

javascript - 如何访问 header

正则表达式匹配分隔符之间的文本

JavaScript 正则表达式替换除第一个和最后一个之外的内容

java - 正则表达式需要包含1个单词

regex - 贪婪/懒惰(非贪婪)/占有量词如何在内部工作?