您好,我无法找到准确的正则表达式来解决我的问题
我有包含 ://
的键,这意味着字符串可以继续 //
如上所说
string
将在 //
之后继续,所以下面的大小写不匹配
getMatchingObj('bins/fs://retrieve/user');
这是我尝试过的:
var pinfoObj = {
['bins/fs://']:{name:'bins',otherinfo:{}},
['library']: {name:'library',otherinfo:{}},
['library/nr']:{name:'nr',otherinfo:{}},
['gt']:{name:'gt',otherinfo:{}}
};
function getMatchingObj(pstr){
var pattern = new RegExp(`^${pstr}(\/(\w*\S+))?`, 'ig');
for(var key in pinfoObj){
if(pattern.test(key)){
return pinfoObj[key];
}
}
}
console.log(getMatchingObj('bins/fs://retrieve/user')); // doesnot match, my string continues after // which is retrieve/user - my intention match this too with above regex
console.log('this works but extact cant be there in real case',getMatchingObj('bins/fs://'));
console.log(getMatchingObj('library/nr')); // matches
console.log(getMatchingObj('gt')); // matches
这是我试图匹配所有测试用例但徒劳的
regex101.com: https://regex101.com/r/3vKZVW/2
预期输出:对于预期的键,我不应该得到非预期的值,或者所有 4 个给定的测试用例都应该匹配
请提前帮助我谢谢!!
最佳答案
已编辑:请检查以下内容:
你解释了//
的特殊含义。在从中生成正则表达式之前,我通过将 //
替换为 //.*
来处理 key 。
另一点:我将 pinfoObj
中的键简化为字符串,因为您使用的数组在用作对象的属性名称之前也会在内部转换为字符串。
const pinfoObj = {
'bins/fs://':{name:'bins',otherinfo:{}},
'library':{name:'library',otherinfo:{}},
'library/nr':{name:'nr',otherinfo:{}},
'gt':{name:'gt',otherinfo:{}}
};
// transform pinfoObj into a form that is
// easier to search through: array keyVal
const keyVal = Object.entries(pinfoObj)
.map(([k,v])=>[new RegExp('^'+k.replace("//","//.*")+'$'),v]);
// console.log(keyVal);
const tst=[
'bins/fs://retrieve/user',
'bins/fs://retrieve/somethingElse',
'this works but extact can\'t be there in real case',
'library/nr',
'gt'
];
function matchingObjVal(keyVal,str){
let fnd=keyVal.find(([k,v])=>k.test(str));
return fnd? fnd[1] : false;
}
tst.map(str=>console.log(str+': ',matchingObjVal(keyVal,str)));
.as-console-wrapper{max-height:100% !important}
关于javascript - 正则表达式基于字符串值匹配对象键,该字符串值可以是精确的或包含键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63088373/