Skip to content

Instantly share code, notes, and snippets.

@akio0911
Forked from feelingplace/Regexp.swift
Last active March 14, 2016 06:01
Show Gist options
  • Save akio0911/d3a0741d072a4be5faf1 to your computer and use it in GitHub Desktop.
Save akio0911/d3a0741d072a4be5faf1 to your computer and use it in GitHub Desktop.
Swift utility class for regular expression
import Foundation
extension String {
func isMatch(regexp:Regexp) -> Bool {
let range = NSMakeRange(0, self.characters.count)
let matches = regexp.internalRegexp.matchesInString(self, options: [], range:range )
return matches.count > 0
}
func matches(regexp:Regexp) -> [String]? {
guard self.isMatch(regexp) else { return nil }
let range = NSMakeRange(0, self.characters.count)
let matches = regexp.internalRegexp.matchesInString( self, options: [], range:range )
return matches.map{ (self as NSString).substringWithRange($0.range) }
}
func replace(regexp:Regexp, replaceString: String) -> String? {
let matchs = regexp.internalRegexp.stringByReplacingMatchesInString(self, options: [], range: NSMakeRange(0, self.characters.count), withTemplate: replaceString)
return matchs
}
}
class Regexp {
let internalRegexp: NSRegularExpression
let pattern: String
init?(_ pattern: String) {
self.pattern = pattern
do {
self.internalRegexp = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
} catch let error as NSError {
print(error.localizedDescription)
self.internalRegexp = NSRegularExpression()
return nil
}
}
func isMatch(input: String) -> Bool {
return input.isMatch(self)
}
func matches(input: String) -> [String]? {
return input.matches(self)
}
func replace(string: String, replaceString: String) -> String? {
return string.replace(self, replaceString: replaceString)
}
}
let pattern: String = "(http|https)://([a-zA-Z0-9]|.)+"
var string: String = "飼い主のブログは http://www.feelingplace.com/ です。"
var replaceString: String = "Feelingplace"
if let regexp = Regexp(pattern),
let title = regexp.replace(string, replaceString: replaceString) {
print(title) //飼い主のブログは Feelingplace です。
}
if let regexp = Regexp(pattern) {
"飼い主のブログは http://www.feelingplace.com/ です。".isMatch(regexp)
if let matches = "飼い主のブログは http://www.feelingplace.com/ です。".matches(regexp) {
for match in matches {
match
}
}
"飼い主のブログは http://www.feelingplace.com/ です。".replace(regexp, replaceString: "Feelingplace")
}
func ~=(r: Regexp, s: String) -> Bool {
return r.isMatch(s)
}
if
let regexpAAA = Regexp("AAA"),
let regexpBBB = Regexp("BBB"),
let regexpCCC = Regexp("CCC")
{
switch "AAX BBX CCC" {
case regexpAAA:
"AAA"
case regexpBBB:
"BBB"
case regexpCCC:
"CCC"
default:
()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment