Skip to content

Commit 73822e9

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 73822e9

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

Sources/_StringProcessing/Regex/Match.swift

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,15 @@ extension Regex {
187187
}
188188

189189
@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 }
190+
@_disfavoredOverload // disambiguate from equatable patterns
191+
public func ~=<R: RegexComponent>(regex: R, input: String) -> Bool {
192+
guard let _ = input.wholeMatch(of: regex) else { return false }
192193
return true
193194
}
194195

195196
@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 }
197+
@_disfavoredOverload // disambiguate from equatable patterns
198+
public func ~=<R: RegexComponent>(regex: R, input: Substring) -> Bool {
199+
guard let _ = input.wholeMatch(of: regex) else { return false }
198200
return true
199201
}

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)