forked from johnno1962/SwiftRegex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwiftRegex.swift
336 lines (278 loc) · 10.7 KB
/
SwiftRegex.swift
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by John Holdsworth on 26/06/2014.
// Copyright (c) 2014 John Holdsworth.
//
// $Id: //depot/SwiftRegex/SwiftRegex.swift#43 $
//
// This code is in the public domain from:
// https://github.com/johnno1962/SwiftRegex
//
import Foundation
private var swiftRegexCache = Dictionary<String,NSRegularExpression>()
public let regexNoGroup = "__nil__"
public class SwiftRegex: NSObject, BooleanType {
let target: NSString
let regex: NSRegularExpression
var regexFile: RegexFile?
init( target:NSString, pattern:String, options:NSRegularExpressionOptions = .DotMatchesLineSeparators ) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
} else {
var error: NSError?
if let regex = NSRegularExpression( pattern: pattern, options:options, error:&error ) {
swiftRegexCache[pattern] = regex
self.regex = regex
} else {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
}
super.init()
}
class func failure( message: String ) {
NSLog( "*** SwiftRegex: \(message)"["%"]["%%"] )
//assert(false,"SwiftRegex: failed")
}
public class func loadFile( path: String, bleat: Bool = true ) -> NSMutableString! {
var error: NSError?
if let string = NSMutableString( contentsOfFile: path, encoding: NSUTF8StringEncoding, error: &error ) {
return string
}
else if bleat {
failure( "Could not load file: \(path), \(error?.localizedDescription)" )
}
return nil
}
public class func saveFile( path: String, newContents: NSString, force: Bool = false ) -> Bool {
let current = force ? nil : loadFile( path, bleat: false )
if current == nil || current != newContents {
var error: NSError?
if !newContents.writeToFile( path, atomically: true, encoding: NSUTF8StringEncoding, error: &error ) {
failure( "Could not write to file: \(path), \(error?.localizedDescription)" )
} else {
return true
}
}
return false
}
public class func patchFile( path: String, replace pattern: String, with template: String ) -> Bool {
var patched = loadFile( path )
patched[pattern] ~= template
return saveFile( path, newContents: patched )
}
final var targetRange: NSRange {
return NSRange(location: 0,length: target.length)
}
final func substring( range: NSRange ) -> String! {
if ( range.location != NSNotFound ) {
return target.substringWithRange(range)
} else {
return nil
}
}
public func doesMatch( options: NSMatchingOptions = nil ) -> Bool {
return range(options: options).location != NSNotFound
}
public func range( options: NSMatchingOptions = nil ) -> NSRange {
return regex.rangeOfFirstMatchInString( target as String, options: nil, range: targetRange )
}
public func match( options: NSMatchingOptions = nil ) -> String! {
return substring( range( options: options ) )
}
public func groups( options: NSMatchingOptions = nil ) -> [String]! {
return groupsForMatch( regex.firstMatchInString(target as String, options: options, range: targetRange) )
}
func groupsForMatch( match: NSTextCheckingResult! ) -> [String]! {
if match != nil {
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring( match.rangeAtIndex(groupno) ) as String! {
groups.append( group )
} else {
groups.append( regexNoGroup ) // avoids bridging problems
}
}
return groups
} else {
return nil
}
}
public subscript( groupno: Int ) -> String! {
get {
if let groups = groups() {
let group = groups[groupno]
return group != regexNoGroup ? group : nil
} else {
return nil
}
}
set( newValue ) {
if let mutableTarget = target as? NSMutableString {
for match in matchResults().reverse() {
let replacement = regex.replacementStringForResult( match,
inString: target as String, offset: 0, template: newValue )
mutableTarget.replaceCharactersInRange( match.rangeAtIndex(groupno), withString: replacement )
}
} else {
SwiftRegex.failure("Group modify on non-mutable")
}
}
}
public subscript( template: String ) -> String {
get {
return replaceWith( template ) as String
}
}
func matchResults( options: NSMatchingOptions = nil ) -> [NSTextCheckingResult] {
return regex.matchesInString( target as String, options: options, range: targetRange ) as! [NSTextCheckingResult]
}
public func ranges( options: NSMatchingOptions = nil ) -> [NSRange] {
return matchResults( options: options ).map { $0.range }
}
public func matches( options: NSMatchingOptions = nil ) -> [String] {
return matchResults( options: options ).map { self.substring($0.range) }
}
public func allGroups( options: NSMatchingOptions = nil ) -> [[String]] {
return matchResults( options: options ).map { self.groupsForMatch($0) }
}
public func dictionary( options: NSMatchingOptions = nil ) -> Dictionary<String,String> {
var out = Dictionary<String,String>()
for match in matchResults(options: options) {
out[substring(match.rangeAtIndex(1))] =
substring(match.rangeAtIndex(2))
}
return out
}
func substituteMatches( substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String ) -> Bool {
let out = NSMutableString()
var pos = 0
regex.enumerateMatchesInString( target as String, options: nil, range: targetRange ) {
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
let matchRange = match.range
out.appendString( self.substring( NSRange(location:pos, length:matchRange.location-pos) ) )
out.appendString( substitution(match, stop) )
pos = matchRange.location + matchRange.length
}
out.appendString( substring( NSRange(location:pos, length:targetRange.length-pos) ) )
if let mutableTarget = target as? NSMutableString {
if out != target {
mutableTarget.setString(out as String)
return true
}
} else {
SwiftRegex.failure("Modify on non-mutable")
}
return false
}
func replaceWith( template: String, options: NSMatchingOptions = nil ) -> NSMutableString {
let mutable = /*target as? NSMutableString ??*/ RegexMutable( target )
regex.replaceMatchesInString( mutable, options: options, range: targetRange, withTemplate: template )
return mutable
}
/* removed Beta6
public func __conversion() -> Bool {
return doesMatch()
}
public func __conversion() -> NSRange {
return range()
}
public func __conversion() -> String {
return match()
}
public func __conversion() -> [String] {
return matches()
}
public func __conversion() -> [[String]] {
return allGroups()
}
public func __conversion() -> [String:String] {
return dictionary()
}
*/
public var boolValue: Bool {
return doesMatch()
}
}
extension NSString {
public subscript( pattern: String, options: NSRegularExpressionOptions ) -> SwiftRegex {
return SwiftRegex( target: self, pattern: pattern, options: options )
}
}
extension String {
public subscript( pattern: String, options: NSRegularExpressionOptions ) -> SwiftRegex {
return SwiftRegex( target: self, pattern: pattern, options: options )
}
}
extension NSString {
public subscript( pattern: String ) -> SwiftRegex {
return SwiftRegex( target: self, pattern: pattern )
}
}
extension String {
public subscript( pattern: String ) -> SwiftRegex {
return SwiftRegex( target: self, pattern: pattern )
}
}
public func RegexMutable( string: NSString ) -> NSMutableString {
return NSMutableString( string: string )
}
// for switch
public var lastRegexMatchGroups: [String!]!
public func ~= ( left: String, right: String ) -> Bool {
if let groups = SwiftRegex( target: right, pattern: left ).groups() {
lastRegexMatchGroups = groups.map { $0 != regexNoGroup ? $0 : nil }
return true
}
return false
}
// for replacements
public func ~= ( left: SwiftRegex, right: String ) -> Bool {
return left.substituteMatches( {
(match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
} )
}
public func ~= ( left: SwiftRegex, right: [String] ) -> Bool {
var matchNumber = 0
return left.substituteMatches( {
(match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in
if ++matchNumber == right.count {
stop.memory = true
}
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
} )
}
public func ~= ( left: SwiftRegex, right: (String) -> String ) -> Bool {
return left.substituteMatches( {
(match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in
return right( left.substring(match.range) )
} )
}
public func ~= ( left: SwiftRegex, right: ([String]) -> String ) -> Bool {
return left.substituteMatches( {
(match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in
return right( left.groupsForMatch(match) )
} )
}
public class RegexFile {
let filepath: String
let contents: NSMutableString!
public init( _ path: String ) {
filepath = path
contents = SwiftRegex.loadFile( path )
}
public subscript( pattern: String ) -> SwiftRegex {
let regex = SwiftRegex( target: contents, pattern: pattern )
regex.regexFile = self // retains until after substitution
return regex
}
deinit {
SwiftRegex.saveFile( filepath, newContents: contents )
}
}