Match.js
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
function Match(pattern,str) {
var step='/';
var keyReg=new RegExp('().*{}+?[]^$\\!','g');
if(typeof pattern!="string"){
throw "pattern 为字符串";
}
pattern=pattern.trim();
patterns=pattern.replace(/^\//,'').split(step);
compile = str.replace(/^\//, '').split(step);
if(patterns.indexOf("**")>-1){
var len=compile.length-patterns.length;
var ind=patterns.indexOf("**");
patterns.splice(ind,1);
compile.splice(ind,len+1);
}
var result="";
patterns=patterns.map(function(rule){
var chat=[],start=false,end=false;
for (var i = 0, len = rule.length, c
; (i < len) && (c = rule.charAt(i))
; i++) {
switch (c) {
case '!':chat.push("!");break;
case '.':chat.push(".");break;
case '*':chat.push("*");break;
case '?':chat.push("?");break;
case '+':chat.push("+");break;
case '@':chat.push("{1}");break;
case '(':start=true;result+=c;break;
case ')':end=true;result+=c;if(start&&end&&chat.length>0){
var r=chat.pop();
if(r==='!'){
result="(?!"+result+").*";
}else{
result+=r;
}
start=false,end=false;
};break;
default:
if(chat.length&&!start){
while(r=chat.shift()){
if(r=='.'){
result+="\\.";
}else if(r==='!'){
result+="[^"+c+"]";
c="";
}else{
result+="[^.]"+r;
}
}
start=false,end=false;
}
result+=c;
}
}
if(chat.length){
while(r=chat.shift()){
if(r=='.'){
result+="\\.";
}else{
result+="[^.]"+r;
}
}
start=false,end=false;
}
return "^"+result+"$";
});
var isSuc=patterns.every(function(rule,index){
var re=new RegExp(rule,"g"),str="";
if(index==patterns.length-1){
str=compile.join('/');
}else{
str=compile.shift();
}
return re.test(str)
});
return isSuc;
}
module.exports= Match;