Why are raw strings the preferred way to write regex patterns and Windows file paths in Kotlin? Show the difference.
answer
- Escaped strings need doubled backslashes
- Raw strings keep one backslash literal
- Two escaping layers collapse to one
- Regex end-anchor $ -> ${'$'}
- Prefer Path/File for real paths
basics
~10 sRegex and Windows paths contain many backslashes. In a normal string you must double each one, which is noisy and error-prone. Raw strings keep backslashes literal, so the pattern reads exactly as intended.
solid answer
~40 sRegex syntax (`\d`, `\w`, `\\` for a literal backslash) and Windows paths (`C:\Users\name`) are full of backslashes. In an **escaped** string the compiler interprets backslashes, so you must **double** every one: `"\\d+"`, `"C:\\Users\\name"`. That doubling is the classic 'leaning toothpick' problem and a frequent source of bugs. A **raw** string does no escape processing, so you write the pattern verbatim: `"""\d+"""` and `"""C:\Users\name"""`. With `Regex("""...""")` the engine sees exactly the characters you typed. Caveat: the regex end-anchor `$` is still a template trigger, so write it as `${'$'}` inside a raw string. Net effect: raw strings make backslash-heavy text dramatically more readable and remove a whole class of escaping errors.
code
kotlin · 5 linesval escaped = Regex("\\d{3}-\\d{4}") // doubled backslashes
val raw = Regex("""\d{3}-\d{4}""") // literal, readable
println(escaped.pattern == raw.pattern) // true: same pattern
val endAnchor = Regex("""err${'$'}""") // $ written via template
println(endAnchor.containsMatchIn("fatal err")) // truego deeper
Knows raw strings avoid doubling backslashes in regex.
Explains the two-layers-of-escaping reason clearly with examples.
Remembers the $ anchor caveat and recommends Path/File for real filesystem work.
Establishes conventions (raw for patterns, structured Path APIs for filesystem) and considers cross-platform correctness.
## The core issue: two layers of escaping With a normal escaped string there are **two** consumers of backslashes: 1. The **Kotlin compiler**, which interprets `\n`, `\t`, `\\`, etc. 2. The **regex engine** (or the filesystem), which interprets `\d`, `\w`, `\.`, etc. So to give the regex engine a single backslash, you must write **two** in the Kotlin source, because the compiler collapses `\\` into one. Patterns become hard to read: ```kotlin val phone = Regex("\\d{3}-\\d{4}") // ugly, error-prone val path = "C:\\Users\\me\\app.log" // every separator doubled ``` ## Raw strings remove one layer A raw string performs **no escape processing**, so the compiler passes backslashes through untouched. Now only the regex engine / filesystem interprets them, and the source matches the intended pattern character-for-character: ```kotlin val phone = Regex("""\d{3}-\d{4}""") // reads like the actual pattern val path = """C:\Users\me\app.log""" ``` This is why Kotlin style guides and the `Regex` docs recommend triple quotes for patterns. ## The $ caveat The regex **end-of-line anchor** `$` is also the template trigger in Kotlin. Inside a raw string you must write it as `${'$'}`: ```kotlin val ends = Regex("""foo${'$'}""") // matches 'foo' at line end ``` Likewise a literal `$` in matched text needs the same treatment. ## Multi-line patterns Raw strings also let you format long patterns across lines (with `RegexOption.COMMENTS` / `(?x)` to ignore whitespace), improving readability of complex expressions. ## Paths: portability note For file paths, prefer building paths with `java.nio.file.Path`/`File` and separators rather than hardcoding Windows backslashes; but when you must show a literal Windows path (logs, examples), a raw string avoids the doubling. ## Summary table | | Escaped string | Raw string | |---|---|---| | `\d+` | `"\\d+"` | `"""\d+"""` | | `C:\a\b` | `"C:\\a\\b"` | `"""C:\a\b"""` | | end anchor `$` | `"...$"` | `"""...${'$'}"""` |
- Why must `$` be written as ${'$'} in a regex raw string?Because $ is Kotlin's string-template trigger; templates still expand in raw strings, so a bare $ would try to interpolate. ${'$'} emits a literal dollar.
- Is `"""\d+"""` and `"\\d+"` equivalent as regex input?Yes — both deliver the same two characters (backslash, d) to the regex engine; the raw form is just far more readable.
An escaped string is like passing a note through a translator who 'helps' by rewriting backslashes; a raw string hands the note over untouched.
saying these in an interview costs you the question
- Doubling backslashes inside a raw-string regex
- Forgetting the $ template caveat in patterns
- Claiming raw strings change regex semantics
- Saying escaped and raw forms produce different patterns
- Hardcoding Windows paths instead of using Path when portability matters