I need to match URLs against string patterns but I want to avoid RegExp to keep the patterns simple and readable.
我需要匹配字符串模式的URL,但我想避免使用RegExp来保持模式的简单性和可读性。
I'd like to be able to have patterns like http://*.example.org/*
, which should be equivalent of /^http:\/\/.*\.example.org\/.*$/
in RegExp. That RegExp should also illustrate why I want to keep it more readable.
我希望能够有像http://*.example.org/*这样的模式,它应该等同于/^http:\ /\/.* \ .example.org \ /。* $ / in正则表达式。 RegExp也应该说明为什么我想让它更具可读性。
Basically I'd like glob-like patterns that work for URLs. The Problem is: normal glob implementations treat /
as a delimiter. That means, http://foo.example.org/bar/bla
wouldn't match my simple pattern.
基本上我喜欢用于URL的类似于glob的模式。问题是:普通的glob实现将/视为分隔符。这意味着,http://foo.example.org/bar/bla与我的简单模式不符。
So, an implementation of glob that can ignore slashes would be great. Is there such a thing or something similar?
所以,一个可以忽略斜杠的glob的实现会很棒。有这样的东西或类似的东西吗?
2 个解决方案
#1
4
You can start with a function like this for glob like behavior:
你可以从像这样的函数开始,用于类似行为的行为:
function glob(pattern, input) {
var re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|\/-])/g, "\\$1").replace(/\*/g, '.*'));
return re.test(input);
}
Then call it as:
然后将其称为:
glob('http://*.example.org/*', 'http://foo.example.org/bar/bla');
true
#2
2
Solved the problem by writing a lib for it:
通过为它编写一个lib解决了这个问题:
https://github.com/lnwdr/calmcard
https://github.com/lnwdr/calmcard
This matches arbitrary strings with simple wildcards.
这将使用简单的通配符匹配任意字符串。
#1
4
You can start with a function like this for glob like behavior:
你可以从像这样的函数开始,用于类似行为的行为:
function glob(pattern, input) {
var re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|\/-])/g, "\\$1").replace(/\*/g, '.*'));
return re.test(input);
}
Then call it as:
然后将其称为:
glob('http://*.example.org/*', 'http://foo.example.org/bar/bla');
true
#2
2
Solved the problem by writing a lib for it:
通过为它编写一个lib解决了这个问题:
https://github.com/lnwdr/calmcard
https://github.com/lnwdr/calmcard
This matches arbitrary strings with simple wildcards.
这将使用简单的通配符匹配任意字符串。