Skip to content

Commit 0e5315b

Browse files
natecook1000milseman
authored andcommitted
Add tests for substring / anchor interaction (swiftlang#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 6c88155 commit 0e5315b

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
@@ -1483,6 +1483,44 @@ extension RegexTests {
14831483
XCTAssertEqual(allRanges.count, 5)
14841484
}
14851485

1486+
func testSubstringAnchors() throws {
1487+
let string = "123abc456def789"
1488+
let trimmed = string.dropFirst(3).dropLast(3) // "abc456def"
1489+
let prefixLetters = try Regex(#"^[a-z]+"#, as: Substring.self)
1490+
let postfixLetters = try Regex(#"[a-z]+$"#, as: Substring.self)
1491+
1492+
// start anchor (^) should match beginning of substring
1493+
XCTExpectFailure {
1494+
XCTAssertEqual(trimmed.firstMatch(of: prefixLetters)?.output, "abc")
1495+
}
1496+
XCTExpectFailure {
1497+
XCTAssertEqual(trimmed.replacing(prefixLetters, with: ""), "456def")
1498+
}
1499+
1500+
// end anchor ($) should match end of substring
1501+
XCTExpectFailure {
1502+
XCTAssertEqual(trimmed.firstMatch(of: postfixLetters)?.output, "def")
1503+
}
1504+
XCTExpectFailure {
1505+
XCTAssertEqual(trimmed.replacing(postfixLetters, with: ""), "abc456")
1506+
}
1507+
1508+
// start anchor (^) should _not_ match beginning of subrange
1509+
XCTAssertEqual(
1510+
string.replacing(
1511+
prefixLetters,
1512+
with: "",
1513+
subrange: trimmed.startIndex..<trimmed.endIndex),
1514+
string)
1515+
// end anchor ($) should _not_ match beginning of subrange
1516+
XCTAssertEqual(
1517+
string.replacing(
1518+
postfixLetters,
1519+
with: "",
1520+
subrange: trimmed.startIndex..<trimmed.endIndex),
1521+
string)
1522+
}
1523+
14861524
func testMatchingOptionsScope() {
14871525
// `.` only matches newlines when the 's' option (single-line mode)
14881526
// is turned on. Standalone option-setting groups (e.g. `(?s)`) are

0 commit comments

Comments
 (0)