Regex to match object key based based on string value which can be exact or contains key

Viewed 956

Hi i have a problem in finding exact regex to solve my problem

I have key which contains :// which means string may continue //

As said above

string will continue after // so below case is not matching

getMatchingObj('bins/fs://retrieve/user');

here is what i have tried:

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

here is what i have tried to match all the test cases but in vain

regex101.com: https://regex101.com/r/3vKZVW/2

Expected Output: with the expected key i should not get un-expected value or all the 4 given test cases should match

please help me thanks in advance!!

2 Answers

Edited: please check the following:

You explained about the special meaning of //. I process the key by replacing // with //.* before I generate a regular expression from it.

Another point: I simplified your keys in pinfoObj to strings, since the arrays you used will internally also be converted to a string before they are applied as a property name for the object.

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}

Rewrite your pattern, so the key is being matched against:

for(var key in pinfoObj){
    var pattern = new RegExp(`^${key}(\/(\w*\S+))?`, 'ig');
    if(pattern.test(pstr)){
        return pinfoObj[key];
    }
}
Related