Last active
February 21, 2018 17:50
-
-
Save unnamedd/74d28d7c5ecbc1214d2d62b139a8ad97 to your computer and use it in GitHub Desktop.
Regular Expression using Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension String { | |
func regex(_ pattern: String) -> Int { | |
let results: [Int] = self.regex(pattern) | |
guard let item = results.first, results.count > 0 else { | |
return NSNotFound | |
} | |
return item | |
} | |
func regex(_ pattern: String) -> [Int] { | |
if let expression = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) { | |
let results = expression.matches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: self.characters.count)) | |
let contents: [Int] = results.flatMap({ | |
let value = (self as NSString).substring(with: $0.rangeAt(1)) | |
let numberFormatter = NumberFormatter() | |
if let number = numberFormatter.number(from: value) { | |
return number.intValue | |
} | |
return nil | |
}) | |
return contents | |
} | |
return [] | |
} | |
} | |
let pattern = "SE-([0-9]+)" | |
let ids = "SE-8740, SE-8741, SE-8742, SE-8743, SE-8744, SE-8745, SE-8746, SE-8747" | |
let test1: [Int] = ids.regex(pattern) | |
print(test1) | |
let test2: Int = ids.regex(pattern) | |
print(test2) | |
let test3: Int = "SE-0140".regex(pattern) | |
print(String(format: "SE-%04i", test3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment