目前我正在传递 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匹配的
正则表达式,然后在获得第 1 组值后,从其末尾提取数字:con
(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(/\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/