Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Sources/SkipLib/Regex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,24 @@ public struct Regex : RegexComponent {
public func replace(_ string: String, with replacement: String) -> String {
return _regex.replace(string, replacement)
}

public func replace(_ string: String, maxReplacements: Int = Int.max, with replacement: (Match) throws -> String) rethrows -> String {
if maxReplacements <= 0 {
return string
}

var replacementCount = 0
return _regex.replace(string) { match in
let replacementValue: String
if replacementCount < maxReplacements {
replacementCount += 1
replacementValue = try replacement(Match(match: match))
} else {
replacementValue = match.value
}
return java.util.regex.Matcher.quoteReplacement(replacementValue)
}
}
}

#endif
4 changes: 4 additions & 0 deletions Sources/SkipLib/Skip/String.kt
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,10 @@ fun String.replacing(regex: Regex, with: String): String {
return regex.replace(this, with)
}

fun String.replacing(regex: Regex, maxReplacements: Int = Int.max, with: (Regex.Match) -> String): String {
return regex.replace(this, maxReplacements = maxReplacements, with = with)
}

operator fun String.Companion.invoke(format: String, vararg args: Any): String {
return format.kotlinFormatString.format(*args)
}
Expand Down
4 changes: 4 additions & 0 deletions Sources/SkipLib/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ public struct String: RandomAccessCollection {
public func replacing(_ regex: Regex, with: String) -> String {
fatalError()
}

public func replacing(_ regex: Regex, maxReplacements: Int = Int.max, with replacement: (Regex.Match) throws -> String) rethrows -> String {
fatalError()
}
}

public struct Substring: RandomAccessCollection {
Expand Down
4 changes: 4 additions & 0 deletions Tests/SkipLibTests/RegexTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ import Testing

#expect("Hello, Alice!" == "Hello, Bob!".replacing(try Regex("Hello, (\\w+)!"), with: "Hello, Alice!"))

#expect("1zz1" == "1z1".replacing(try Regex("([a-z])"), with: { match in
return match[1].substring! + match[1].substring!
}))

#if SKIP
// skip: regular expression support is incomplete
return
Expand Down