目前,我正在传递h-3678/q-55/con-0.11
这样的URL参数,但是由于我的最新开发,我需要能够在 con 参数内传递一个负号,例如:{{1} },但是使用我现在得到的表达式会引发错误?
h-3678/q-55/con--0.5/
答案 0 :(得分:2)
如果您的电话号码总是在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
单词边界仅当它不是另一个单词的一部分,也不在其前面带有数字或{{1}时才匹配con
})_
-文字子字符串con-
-第1组((-?\d+(?:\.\d+)?)
值):
con_match[1]
-可选的连字符-?
-1个以上数字\d+
-1或0次出现(?:\.\d+)?
,然后出现1+个数字 假设.
和最后一个数字之间可能存在任何文本,则可以使用con
正则表达式提取con
匹配项,然后在获得组1的值,从其末尾提取数字:
/\b(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+)?)$/
-连字符-
-第1组:
(-?\d+(?:\.\d+)?)
-可选的连字符-?
-1个以上数字\d+
-1或0次出现(?:\.\d+)?
,然后出现1+个数字.
-字符串的结尾。答案 1 :(得分:0)
//var str = 'h-3678/q-55/con-0.11';
var str = 'h-3678/q-55/con--0.5/';
let con_match = str.match(/(con\-([^\/]+)?)/);
let con = 0;
if (con_match && con_match.length) {
console.log(con_match);
con = con_match[2];
}
console.log(con);
第一个返回: 0.11
第二个返回: -0.5