Skip to content

Commit 88004de

Browse files
committed
Generic ~= operator
Make `~=` generic over `RegexComponent` so that one can use builder components, e.g. `OneOrMore(...)`, or custom-consuming regex components as patterns.
1 parent 6fab471 commit 88004de

File tree

3 files changed

+55
-13
lines changed

3 files changed

+55
-13
lines changed

Sources/_StringProcessing/Regex/Core.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ public struct Regex<Output>: RegexComponent {
6161
}
6262
}
6363

64+
@available(SwiftStdlib 5.7, *)
65+
extension Regex {
66+
public init(quoting string: String) {
67+
self.init(node: .quotedLiteral(string))
68+
}
69+
}
70+
6471
@available(SwiftStdlib 5.7, *)
6572
extension Regex {
6673
/// A program representation that caches any lowered representation for

Sources/_StringProcessing/Regex/Match.swift

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -180,20 +180,11 @@ extension BidirectionalCollection where SubSequence == Substring {
180180
}
181181

182182
@available(SwiftStdlib 5.7, *)
183-
extension Regex {
184-
public init(quoting string: String) {
185-
self.init(node: .quotedLiteral(string))
186-
}
187-
}
188-
189-
@available(SwiftStdlib 5.7, *)
190-
public func ~=<Output>(regex: Regex<Output>, input: String) -> Bool {
191-
guard let _ = try? regex.wholeMatch(in: input) else { return false }
192-
return true
183+
public func ~=<R: RegexComponent>(regex: R, input: String) -> Bool {
184+
input.wholeMatch(of: regex) != nil
193185
}
194186

195187
@available(SwiftStdlib 5.7, *)
196-
public func ~=<Output>(regex: Regex<Output>, input: Substring) -> Bool {
197-
guard let _ = try? regex.wholeMatch(in: input) else { return false }
198-
return true
188+
public func ~=<R: RegexComponent>(regex: R, input: Substring) -> Bool {
189+
input.wholeMatch(of: regex) != nil
199190
}

Tests/RegexBuilderTests/AlgorithmsTests.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,48 @@ class RegexConsumerTests: XCTestCase {
104104
result: "9+16, 3, 10, 99+1")
105105
)
106106
}
107+
108+
func testSwitches() {
109+
// Failure cases
110+
do {
111+
switch "abcde" {
112+
case Regex {
113+
"a"
114+
ZeroOrMore(.any)
115+
"f"
116+
}:
117+
XCTFail()
118+
119+
case "abc":
120+
XCTFail()
121+
122+
case Regex {
123+
"a"
124+
"b"
125+
"c"
126+
}:
127+
XCTFail()
128+
129+
default:
130+
break
131+
}
132+
}
133+
// Success cases
134+
do {
135+
let input = "abcde"
136+
137+
guard case Regex({
138+
"a"
139+
ZeroOrMore(.any)
140+
"e"
141+
}) = input else {
142+
XCTFail()
143+
}
144+
145+
guard case OneOrMore(.word) = input else {
146+
XCTFail()
147+
return
148+
}
149+
}
150+
}
107151
}

0 commit comments

Comments
 (0)