javascript - 正则表达式基于字符串值匹配对象键,该字符串值可以是精确的或包含键

标签 javascript jquery regex

您好,我无法找到准确的正则表达式来解决我的问题

我有包含 :// 的键,这意味着字符串可以继续 //

如上所说

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/

相关文章:

javascript - 如何计算两点之间的 Angular ?

javascript - 排除正则表达式中的字符串

Java 正则表达式精确匹配带有特殊字符的单词

Ruby:将嵌套数组的字符串表示形式解析为数组?

javascript - 如何获取沿饼图边缘的切片坐标?

javascript - Angular 指令模板的增量值

javascript - 获取方法 javascript 传递 cookie

c# - AJAX PUT 请求到 C# Controller

java - 使用 JQuery 消费 Java Web 服务 : Error?

javascript - 条件验证 - Jquery