5

As you probably all know, regular expressions have some metacharacters, such as \, |, ., ?, +, *,…. If you want to search for a substring including one of these characters without actually using the regex behaviour, you can escape it with a backslash.

So if you want to search for "Is it true?" in a string you would use the pattern "Is it true\?".

I am using Kotlin and its built-in regular expressions. Is there a way in Kotlin (a function or something) to get a string from another string in which all of the special characters in the input string are escaped?

So if the input to such a function were "This is good." the output would be "This is good\.", and for "? a [+" it would be "\? a \[\+". → every regex special character in the output is escaped with a backslash.

5
  • 4
    Are you looking for kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/…? Commented Dec 25, 2022 at 3:53
  • Frame challenge: if you want to search for a literal string, why are you using a regex? There are simpler (and more efficient) ways to search for a literal string. Commented Dec 26, 2022 at 11:51
  • @gidds Good to raise alternatives, but in general, there is a use case for regex-escaping, as the literal string may well be part of a bigger regex. Commented Dec 26, 2022 at 14:35
  • Yes Regex.escape (kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/…) is what I was looking for. Thank you. Commented Dec 28, 2022 at 20:25
  • I was trying escapeReplacement but that didn't work. Glad I found your comment... Commented May 19, 2023 at 22:07

1 Answer 1

1

Use Regex.fromLiteral() function:

val regex = Regex.fromLiteral("? a [+")
println("? a [+" matches regex) // true

As said by @Slaw in comments, you can also use Regex.escape() function:

val escaped = Regex.escape("? a [+")
println("? a [+" matches Regex(escaped)) // true
Sign up to request clarification or add additional context in comments.

3 Comments

The documentation of the two functions is identical. Do you know why both exist?
fromLiteral returns a Regex but escape returns a String.
So escape is likely to be more useful if you need to combine it with some other string before converting the result to a Regex. Which is the common reason for needing this functionality in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.