How to match a long path among many short versions
DECISION:
var str = this.path;
var spltd = str.split('/');
var agg = '(?:';
var e = 'Item';
for (i = 0; i < spltd.length-2; i++) { agg += '(?:';}
var newstr = '^(?:\/?'+agg+spltd.join('\/)?')+'::)?'+e;
var regex = new RegExp(newstr);
var check = str.match(regex);
console.log(check); // Works on the good cases, not on the bad
thanks to @Rodrigo López
THE PROBLEM WAS:
I am trying to set up exploratory functionality .
Basically, I have paths
like:
Item Path::Item /Path::Item Long/Path::Item /Long/Path::Item Very/Long/Path::Item /Very/Long/Path::Item Very/Very/Long/Path::Item /Very/Very/Long/Path::Item My/Very/Very/Long/Path::Item
Stored in javascript Object
. Now I need .match()
any of the theses using full path
:
My/Very/Very/Long/Path::Item
This side is not easier ...
I tried:
//NOTE : if it match it returns 'OK'
var str = 'My/Very/Very/Long/Path';
var spltd = str.split('/');
var newstr = '('+spltd.join('/)?(')+')$';//alert(newstr);
var regex = new RegExp(newstr);
var check = str.match(regex);
console.log(check); // 'OK'
I can't say it won't work, but it's still far from accurate. It returns ' OK
' in too many cases ....
How when str =
My/Very/Long/Path::Item My/Long/Path::Item Very/Path::Item etc.
This is completely unacceptable.
source to share
Its not pretty, but this Regex does the job:
^(?:\/?(?:(?:(?:(?:My\/)?Very\/)?Very\/)?Long\/)?Path::)?Item
You can change your code to this:
var str = 'My/Very/Very/Long/Path::Item';
var regex = new RegExp('^(?:\\/?(?:(?:(?:(?:My\\/)?Very\\/)?Very\\/)?Long\\/)?Path::)?Item');
var check = str.match(regex);
Tested on Regexr.com:
Note. If its a match it returns a match, out of order, and if it doesn't match, it returns null
source to share