Skip to content

Commit

Permalink
KT-50173 Fix Regex.escapeReplacement function in JS
Browse files Browse the repository at this point in the history
(cherry picked from commit a829a67)
  • Loading branch information
ilya-g committed Dec 12, 2021
1 parent c71e090 commit 72551e4
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion libraries/stdlib/js/src/kotlin/text/regex.kt
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ public actual class Regex actual constructor(pattern: String, options: Set<Regex
public actual fun escapeReplacement(literal: String): String = literal.nativeReplace(replacementEscape, "\\$&")

private val patternEscape = RegExp("""[\\^$*+?.()|[\]{}]""", "g")
private val replacementEscape = RegExp("""[\$]""", "g")
private val replacementEscape = RegExp("""[\\$]""", "g")

internal fun nativeEscapeReplacement(literal: String): String = literal.nativeReplace(nativeReplacementEscape, "$$$$")
private val nativeReplacementEscape = RegExp("""\$""", "g")
Expand Down
5 changes: 4 additions & 1 deletion libraries/stdlib/test/text/RegexTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,10 @@ class RegexTest {
// inserts the first captured group
assertEquals("(123)-(456)", pattern.replace(input, "($1)"))

assertEquals("$&-$&", pattern.replace(input, Regex.escapeReplacement("$&")))
for (r in listOf("$&", "\\$", "\\ $", "$\\")) {
assertEquals("$r-$r", pattern.replace(input, Regex.escapeReplacement(r)))
}

assertEquals("X-456", pattern.replaceFirst(input, "X"))

val longInput = "0123456789ABC"
Expand Down

0 comments on commit 72551e4

Please sign in to comment.