-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add utility the emphasize case insensitive portions of strings (#810)
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
// | ||
// String+EmphasizedMatching.swift | ||
// | ||
// | ||
// Created by Greg Bolsinga on 6/15/24. | ||
// | ||
|
||
import Foundation | ||
import RegexBuilder | ||
|
||
extension String { | ||
func emphasized(matching fragment: String) -> String { | ||
let regex = Regex { | ||
Capture { | ||
fragment | ||
} | ||
} | ||
.ignoresCase() | ||
|
||
return self.replacing(regex, maxReplacements: 1) { | ||
let (_, m) = $0.output | ||
return "**\(m)**" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// | ||
// EmphasizedMatchingTests.swift | ||
// | ||
// | ||
// Created by Greg Bolsinga on 6/15/24. | ||
// | ||
|
||
import XCTest | ||
|
||
@testable import Site | ||
|
||
final class EmphasizedMatchingTests: XCTestCase { | ||
func testJustOneLetterMatchingWithOneMatch() throws { | ||
XCTAssertEqual("Gre".emphasized(matching: "G"), "**G**re") | ||
XCTAssertEqual("Gre".emphasized(matching: "g"), "**G**re") | ||
} | ||
|
||
func testJustOneLetterMatchinWithMultipleMatches() throws { | ||
XCTAssertEqual("Greg".emphasized(matching: "G"), "**G**reg") | ||
XCTAssertEqual("Greg".emphasized(matching: "g"), "**G**reg") | ||
} | ||
|
||
func testTwoLettersMatchingWithOneMatch() throws { | ||
XCTAssertEqual("Greg".emphasized(matching: "Gr"), "**Gr**eg") | ||
XCTAssertEqual("Greg".emphasized(matching: "gr"), "**Gr**eg") | ||
} | ||
|
||
func testTwoLettersMatchingWithMultipleMatches() throws { | ||
XCTAssertEqual("Gregr".emphasized(matching: "Gr"), "**Gr**egr") | ||
XCTAssertEqual("GregR".emphasized(matching: "gr"), "**Gr**egR") | ||
} | ||
} |