diff --git a/Sources/_StringProcessing/Regex/Core.swift b/Sources/_StringProcessing/Regex/Core.swift index d77784df4..36d62f674 100644 --- a/Sources/_StringProcessing/Regex/Core.swift +++ b/Sources/_StringProcessing/Regex/Core.swift @@ -61,6 +61,13 @@ public struct Regex: RegexComponent { } } +@available(SwiftStdlib 5.7, *) +extension Regex { + public init(quoting string: String) { + self.init(node: .quotedLiteral(string)) + } +} + @available(SwiftStdlib 5.7, *) extension Regex { /// A program representation that caches any lowered representation for diff --git a/Sources/_StringProcessing/Regex/Match.swift b/Sources/_StringProcessing/Regex/Match.swift index 39ff7ece9..45df7aeaa 100644 --- a/Sources/_StringProcessing/Regex/Match.swift +++ b/Sources/_StringProcessing/Regex/Match.swift @@ -180,20 +180,12 @@ extension BidirectionalCollection where SubSequence == Substring { } @available(SwiftStdlib 5.7, *) -extension Regex { - public init(quoting string: String) { - self.init(node: .quotedLiteral(string)) +extension RegexComponent { + public static func ~=(regex: Self, input: String) -> Bool { + input.wholeMatch(of: regex) != nil } -} -@available(SwiftStdlib 5.7, *) -public func ~=(regex: Regex, input: String) -> Bool { - guard let _ = try? regex.wholeMatch(in: input) else { return false } - return true -} - -@available(SwiftStdlib 5.7, *) -public func ~=(regex: Regex, input: Substring) -> Bool { - guard let _ = try? regex.wholeMatch(in: input) else { return false } - return true + public static func ~=(regex: Self, input: Substring) -> Bool { + input.wholeMatch(of: regex) != nil + } } diff --git a/Tests/RegexBuilderTests/AlgorithmsTests.swift b/Tests/RegexBuilderTests/AlgorithmsTests.swift index 5a7a69fac..97fccde01 100644 --- a/Tests/RegexBuilderTests/AlgorithmsTests.swift +++ b/Tests/RegexBuilderTests/AlgorithmsTests.swift @@ -104,4 +104,61 @@ class RegexConsumerTests: XCTestCase { result: "9+16, 3, 10, 99+1") ) } + + func testSwitches() { + // Failure cases + do { + switch "abcde" { + case Regex { + "a" + ZeroOrMore(.any) + "f" + }: + XCTFail() + + case "abc": + XCTFail() + + case Regex { + "a" + "b" + "c" + }: + XCTFail() + + default: + break + } + } + // Success cases + do { + let input = "abcde" + + switch input { + case Regex { + "a" + ZeroOrMore(.any) + "e" + }: + break + + default: + XCTFail() + } + + guard case Regex({ + "a" + ZeroOrMore(.any) + "e" + }) = input else { + XCTFail() + return + } + + guard case OneOrMore(.word) = input else { + XCTFail() + return + } + } + } }