Skip to content

Commit

Permalink
Merge pull request #16 from cradnovich/feature/regex-match-substring
Browse files Browse the repository at this point in the history
Pure Swift extension methods for getting substrings from RegularExpressionMatch.Range and Range<Int>
  • Loading branch information
colemancda committed Dec 13, 2015
2 parents 2256b2b + 74aacb9 commit a65a2f6
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Sources/RegularExpression.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,18 @@ public struct RegularExpressionMatch {
}
}

public extension String {
func substring(range: RegularExpressionMatch.Range) -> String? {
switch range {
case .NotFound:
return nil
case let .Found(r):
return substring(r)
}
}

func substring(range: Range<Int>) -> String? {
let indexRange = Swift.Range(start: utf8.startIndex.advancedBy(range.startIndex), end: utf8.startIndex.advancedBy(range.endIndex))
return String(utf8[indexRange])
}
}
2 changes: 2 additions & 0 deletions SwiftFoundation/SwiftFoundation.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,9 @@
6E30BA1B1B40F543009B1B49 /* SwiftFoundationTests */,
6E30BA0E1B40F543009B1B49 /* Products */,
);
indentWidth = 4;
sourceTree = "<group>";
tabWidth = 4;
};
6E30BA0E1B40F543009B1B49 /* Products */ = {
isa = PBXGroup;
Expand Down
33 changes: 33 additions & 0 deletions Tests/RegularExpressionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,39 @@ class RegularExpressionTests: XCTestCase {

XCTAssert(match.subexpressionRanges.count == regex.subexpressionsCount, "Subexpressions should be \(regex.subexpressionsCount), is \(match.subexpressionRanges.count)")
}

func testEmoji() {

let testString = "🙄😒🍺🦄"

let beer = "🍺"

let pattern = "\\(\(beer)\\)"

do {
let beerFinder = try RegularExpression(pattern)

guard let match = beerFinder.match(testString) else {
XCTFail("Could not find 🍺 in \(testString)")
return
}

guard let beerRange = match.subexpressionRanges.first else {
XCTFail("Could not find 🍺 capture group despite \(testString) match \(match)")
return
}

guard let capturedString = testString.substring(beerRange) else {
XCTFail("Failed to get a substring with range \(beerRange) in \(testString)")
return
}

XCTAssertEqual(beer, capturedString, "Captured substring in \(beerRange) should match \(beer), but instead is \(capturedString)")
} catch {

XCTFail("Error thrown trying to create RegularExpression from \(pattern): \(error)")
}
}
}


0 comments on commit a65a2f6

Please sign in to comment.