简体   繁体   中英

Dynamically compare accuracy of regex patterns for match

Supposing I have two regexes and both match a string, but one of them matches it in a stricter way, is there a way to figure that out programmatically?

For example, I'm matching this string:

/path/on/file/system

and I have the following two regular expressions:

const opt1 = /\/path\/on/;
const opt2 = /\/path/;

I can see with my eyes that opt1 is stricter, but how can javascript know about that?

Is converting the regex to a string and checking for character length a good measure of strictness?

You can implement this function by:

Sorting your regular expressions by length.

loop through your sorted regular expressions array to check if there is a match

then return the most strict matching element.

 function check(arrayOfRegEx, str) { //sort the regex array by length var sortedArr = arrayOfRegEx.sort(function(a, b) { return a.toString().length - b.toString().length || a.toString().localeCompare(b); }); let mostStrict = ''; sortedArr.forEach(function(reg) { if(new RegExp((reg.toString()).replace(/\\\\/g, "").substring(1)).test(str)) { mostStrict = reg; } }); return mostStrict; } var result = check([/\\/path/, /\\/test\\/test/, /\\/path\\/on/], '/path/on/file/system'); console.log(result); // returns /\\/path\\/on/ 

And of course you can tweak this function to fit your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM