Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pure Swift extension methods for getting substrings from RegularExpressionMatch.Range and Range<Int> #16

Merged
merged 7 commits into from
Dec 13, 2015
Merged
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)")
}
}
}