From 3684fe9c1b8d1fe3eabd6b285d535c5602562539 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Wed, 15 Jun 2022 17:12:26 -0500 Subject: [PATCH 1/2] Add tests for substring / anchor interaction ^ and $ should match the start and end of the callee, even if that callee is a substring. Right now ^ and $ match the start and end of the callee's base string, instead. In addition, ^ and $ should only match the start and end of the callee when replacing a subrange, not the start and end of the subrange. --- Tests/RegexTests/MatchTests.swift | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Tests/RegexTests/MatchTests.swift b/Tests/RegexTests/MatchTests.swift index e0f391507..e4e8b78a6 100644 --- a/Tests/RegexTests/MatchTests.swift +++ b/Tests/RegexTests/MatchTests.swift @@ -1397,6 +1397,38 @@ extension RegexTests { XCTAssertEqual(allRanges.count, 5) } + func testSubstringAnchors() throws { + let string = "123abc456def789" + let trimmed = string.dropFirst(3).dropLast(3) // "abc456def" + let prefixLetters = try Regex(#"^[a-z]+"#, as: Substring.self) + let postfixLetters = try Regex(#"[a-z]+$"#, as: Substring.self) + + XCTExpectFailure { + // start anchor (^) should match beginning of substring + XCTAssertEqual(trimmed.firstMatch(of: prefixLetters)?.output, "abc") + XCTAssertEqual(trimmed.replacing(prefixLetters, with: ""), "456def") + + // end anchor ($) should match end of substring + XCTAssertEqual(trimmed.firstMatch(of: postfixLetters)?.output, "def") + XCTAssertEqual(trimmed.replacing(postfixLetters, with: ""), "abc456") + } + + // start anchor (^) should _not_ match beginning of subrange + XCTAssertEqual( + string.replacing( + prefixLetters, + with: "", + subrange: trimmed.startIndex.. Date: Wed, 15 Jun 2022 23:26:43 -0500 Subject: [PATCH 2/2] One test failure per expectFailure --- Tests/RegexTests/MatchTests.swift | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Tests/RegexTests/MatchTests.swift b/Tests/RegexTests/MatchTests.swift index e4e8b78a6..3c5ac96eb 100644 --- a/Tests/RegexTests/MatchTests.swift +++ b/Tests/RegexTests/MatchTests.swift @@ -1403,13 +1403,19 @@ extension RegexTests { let prefixLetters = try Regex(#"^[a-z]+"#, as: Substring.self) let postfixLetters = try Regex(#"[a-z]+$"#, as: Substring.self) + // start anchor (^) should match beginning of substring XCTExpectFailure { - // start anchor (^) should match beginning of substring XCTAssertEqual(trimmed.firstMatch(of: prefixLetters)?.output, "abc") + } + XCTExpectFailure { XCTAssertEqual(trimmed.replacing(prefixLetters, with: ""), "456def") - - // end anchor ($) should match end of substring + } + + // end anchor ($) should match end of substring + XCTExpectFailure { XCTAssertEqual(trimmed.firstMatch(of: postfixLetters)?.output, "def") + } + XCTExpectFailure { XCTAssertEqual(trimmed.replacing(postfixLetters, with: ""), "abc456") }