Skip to content

Instantly share code, notes, and snippets.

@feelingplace
Forked from takafumir/Regexp.swift
Last active March 11, 2016 13:06
Show Gist options
  • Save feelingplace/4ecaaf665af255c77eaa to your computer and use it in GitHub Desktop.
Save feelingplace/4ecaaf665af255c77eaa to your computer and use it in GitHub Desktop.
Swift utility class for regular expression
import Foundation
class Regexp {
let internalRegexp: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
do {
self.internalRegexp = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
} catch let error as NSError {
print(error.localizedDescription)
self.internalRegexp = NSRegularExpression()
}
}
func isMatch(input: String) -> Bool {
let matches = self.internalRegexp.matchesInString( input, options: [], range:NSMakeRange(0, input.characters.count) )
return matches.count > 0
}
func matches(input: String) -> [String]? {
if self.isMatch(input) {
let matches = self.internalRegexp.matchesInString( input, options: [], range:NSMakeRange(0, input.characters.count) )
var results: [String] = []
for i in 0 ..< matches.count {
results.append( (input as NSString).substringWithRange(matches[i].range) )
}
return results
}
return nil
}
func replace(string: String, replaceString: String) -> String? {
let matchs = self.internalRegexp.stringByReplacingMatchesInString(string, options: [], range: NSMakeRange(0, string.characters.count), withTemplate: replaceString)
return matchs
}
}
@feelingplace
Copy link
Author

Add func replace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment