Skip to content

Instantly share code, notes, and snippets.

@neoneye
Created Nov 28, 2016
Embed
What would you like to do?
Extract regex matches
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map { result.rangeAt($0).location != NSNotFound
? nsString.substring(with: result.rangeAt($0))
: ""
}
}
}
}
class MatchingStringTests: XCTestCase {
func test1() {
let actual = "prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])").description
let expected = [["fix12", "1", "2"], ["fix45", "4", "5"]].description
XCTAssertEqual(actual, expected)
}
func test2() {
let actual = "prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)").description
let expected = [["prefix12", "12"]].description
XCTAssertEqual(actual, expected)
}
func test3() {
let actual = "12".matchingStrings(regex: "(?:prefix)?([0-9]+)").description
let expected = [["12", "12"]].description
XCTAssertEqual(actual, expected)
}
func test4() {
let actual = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1].description
let expected = "12".description
XCTAssertEqual(actual, expected)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment