Skip to content

Commit 511c665

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 511c665

File tree

3 files changed

+47
-13
lines changed

3 files changed

+47
-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: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -180,20 +180,13 @@ 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+
@_disfavoredOverload // disambiguate from equatable patterns
184+
public func ~=<R: RegexComponent>(regex: R, input: String) -> Bool {
185+
input.wholeMatch(of: regex) != nil
193186
}
194187

195188
@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
189+
@_disfavoredOverload // disambiguate from equatable patterns
190+
public func ~=<R: RegexComponent>(regex: R, input: Substring) -> Bool {
191+
input.wholeMatch(of: regex) != nil
199192
}

Tests/RegexBuilderTests/AlgorithmsTests.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,38 @@ class RegexConsumerTests: XCTestCase {
104104
result: "9+16, 3, 10, 99+1")
105105
)
106106
}
107+
108+
func testSwitches() {
109+
switch "abcde" {
110+
case Regex {
111+
"a"
112+
ZeroOrMore(.any)
113+
"f"
114+
}:
115+
XCTFail()
116+
117+
case "abc":
118+
XCTFail()
119+
120+
case Regex {
121+
"a"
122+
"b"
123+
"c"
124+
}:
125+
XCTFail()
126+
127+
case Regex {
128+
"a"
129+
ZeroOrMore(.any)
130+
"e"
131+
}:
132+
break // success
133+
134+
case OneOrMore(.word):
135+
break // success
136+
137+
default:
138+
XCTFail()
139+
}
140+
}
107141
}

0 commit comments

Comments
 (0)