Skip to content

Add CustomRegexComponent example #196

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

Merged
merged 2 commits into from
Mar 2, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Tests/RegexTests/RegexDSLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,66 @@ class RegexDSLTests: XCTestCase {
}
}
}

func testSemanticVersionExample() {
struct SemanticVersion: Equatable {
var major: Int
var minor: Int
var patch: Int
var dev: String?
}
struct SemanticVersionParser: CustomRegexComponent {
typealias Match = SemanticVersion
func match(
_ input: String,
startingAt index: String.Index,
in bounds: Range<String.Index>
) -> (upperBound: String.Index, match: SemanticVersion)? {
let regex = Regex {
tryCapture(oneOrMore(.digit)) { Int($0) }
"."
tryCapture(oneOrMore(.digit)) { Int($0) }
optionally {
"."
tryCapture(oneOrMore(.digit)) { Int($0) }
}
optionally {
"-"
capture(oneOrMore(.word))
}
}

guard let match = input[index..<bounds.upperBound].firstMatch(of: regex),
match.range.lowerBound == index
else { return nil }

let result = SemanticVersion(
major: match.result.1,
minor: match.result.2,
patch: match.result.3 ?? 0,
dev: match.result.4.map(String.init))
return (match.range.upperBound, result)
}
}

let versions = [
("1.0", SemanticVersion(major: 1, minor: 0, patch: 0)),
("1.0.1", SemanticVersion(major: 1, minor: 0, patch: 1)),
("12.100.5-dev", SemanticVersion(major: 12, minor: 100, patch: 5, dev: "dev")),
]

let regex = Regex {
capture(SemanticVersionParser())
}
for (str, version) in versions {
XCTAssertEqual(str.match(regex)?.match.1, version)
}
// FIXME: This yields an assertion in TypeConstruction.tupleType(_:)
// "Assertion failed: A one-element tuple is not a realistic Swift type"
// for (str, version) in versions {
// XCTAssertEqual(str.match(SemanticVersionParser())?.match, version)
// }
}
}

extension Unicode.Scalar {
Expand Down