Skip to content

Commit 55ffc5c

Browse files
authored
Add tests for substring / anchor interaction (#490)
^ 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.
1 parent 2265620 commit 55ffc5c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Tests/RegexTests/MatchTests.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1397,6 +1397,44 @@ extension RegexTests {
13971397
XCTAssertEqual(allRanges.count, 5)
13981398
}
13991399

1400+
func testSubstringAnchors() throws {
1401+
let string = "123abc456def789"
1402+
let trimmed = string.dropFirst(3).dropLast(3) // "abc456def"
1403+
let prefixLetters = try Regex(#"^[a-z]+"#, as: Substring.self)
1404+
let postfixLetters = try Regex(#"[a-z]+$"#, as: Substring.self)
1405+
1406+
// start anchor (^) should match beginning of substring
1407+
XCTExpectFailure {
1408+
XCTAssertEqual(trimmed.firstMatch(of: prefixLetters)?.output, "abc")
1409+
}
1410+
XCTExpectFailure {
1411+
XCTAssertEqual(trimmed.replacing(prefixLetters, with: ""), "456def")
1412+
}
1413+
1414+
// end anchor ($) should match end of substring
1415+
XCTExpectFailure {
1416+
XCTAssertEqual(trimmed.firstMatch(of: postfixLetters)?.output, "def")
1417+
}
1418+
XCTExpectFailure {
1419+
XCTAssertEqual(trimmed.replacing(postfixLetters, with: ""), "abc456")
1420+
}
1421+
1422+
// start anchor (^) should _not_ match beginning of subrange
1423+
XCTAssertEqual(
1424+
string.replacing(
1425+
prefixLetters,
1426+
with: "",
1427+
subrange: trimmed.startIndex..<trimmed.endIndex),
1428+
string)
1429+
// end anchor ($) should _not_ match beginning of subrange
1430+
XCTAssertEqual(
1431+
string.replacing(
1432+
postfixLetters,
1433+
with: "",
1434+
subrange: trimmed.startIndex..<trimmed.endIndex),
1435+
string)
1436+
}
1437+
14001438
func testMatchingOptionsScope() {
14011439
// `.` only matches newlines when the 's' option (single-line mode)
14021440
// is turned on. Standalone option-setting groups (e.g. `(?s)`) are

0 commit comments

Comments
 (0)