-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
123 lines (99 loc) · 2.53 KB
/
index.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
var defaultSource = "(?:)"
function toArray(arg){
return [].slice.call(arg)
}
function regexp () {
if(this.constructor !== regexp) return new regexp()
this.source = defaultSource
}
regexp.number = "[0-9]"
regexp.lower = "[a-z]"
regexp.upper = "[A-Z]"
regexp.letter = "[a-zA-Z]"
regexp.tab = "\\t"
regexp.space = "\\s"
regexp.word = "\\w"
regexp.digit = "\\d"
regexp.newline = "\\n"
regexp.return = "\\r"
regexp.eol = "(?:(?:\\n)|(?:\\r\\n))"
regexp.naming = {}
regexp.escape = function (source){
if (source == null) return ""
return String(source).replace( /([.*+?^=!:${}()|[\]\/\\])/g, "\\$1" )
}
regexp.prototype.add = function(){
if(this.source == defaultSource){
this.source = ""
}
this.source += toArray(arguments).join("")
return this
}
regexp.prototype.start = function(val){
return this.add( "^", regexp.escape(val) )
}
/**
* .must('a').atleast(3)
*/
regexp.prototype.atleast = function(times){
return this.add( "{", times, ",}" )
}
/**
* .must('a').has(1, 5)
* .must('a').has(5)
*/
regexp.prototype.has = function(){
return this.add( "{", toArray(arguments).join(","), "}" )
}
regexp.prototype.must = function(val){
return this.add( regexp.escape(val) )
}
regexp.prototype.maybe = function(val){
return this.add( "(?:", regexp.escape(val), ")?" )
}
regexp.prototype.something = function(){
return this.add( "(?:.)+" )
}
regexp.prototype.anything = function(){
return this.add( "(?:.)*" )
}
regexp.prototype.anythingBut = function(val){
return this.add( "(?:[^", val, "])*" )
}
regexp.prototype.somethingBut = function(val){
return this.add( "(?:[^", val, "])+" )
}
regexp.prototype.find = function(val){
return this.add( "(", val, ")" )
}
/**
* either("org", "com", "net")
*/
regexp.prototype.either = function(){
return this.add( "(?:", toArray(arguments).join("|"), ")" )
}
regexp.prototype.end = function(val){
return this.add( regexp.escape(val), "$" )
}
regexp.prototype.global = function(){
this.globalFlag = true
return this
}
regexp.prototype.ignoreCase = function(){
this.ignoreCaseFlag = true
return this
}
regexp.prototype.multiline = function(){
this.multilineFlag = true
return this
}
regexp.prototype.toRegExp = function(name){
var flags = (this.multilineFlag? "m": "") + (this.ignoreCaseFlag? "i": "") + (this.globalFlag? "g": "")
var re = new RegExp(this.source, flags)
if(name) regexp.naming[name] = re
return re
}
regexp.prototype.toString = function(){
return this.source
}
module.exports = regexp