Explain Codes LogoExplain Codes Logo

What are all the escape characters?

java
regex-engineering
unicode-escapes
string-manipulation
Alex KataevbyAlex Kataev·Sep 29, 2024
TLDR

Java escape characters signal specific instructions within strings:

  • \n: New line
  • \t: Tab
  • \": Double quote
  • \\: Backslash

An example to illustrate this:

// The following string when printed, showcases escape sequences in action: String text = "Line 1\n\tLine 2 with \"quotes\" and \\";

Appreciating escape characters in Java requires understanding Unicode escapes (\u prefixed). For instance, \u00A9 adds a flair of copyright © to your strings.

Regex and Unicode escapades

With Unicode escapes, such as \u2021, Java strings accommodates a wide variety of characters, from international symbols to emoji. However, tread carefully with supplementary characters, those beyond the Basic Multilingual Plane (BMP). These characters need two Unicode escapes, a surrogate pair, for proper representation.

Regex masters, beware! Certain Java versions honor \v as vertical whitespace, which could turn your regex character classes head over heels.

Practical escape sequence applications

Escape sequences make string manipulation in Java a breeze.

  • File paths: Double backslashes to denote a directory path, just like C:\\Directory\\file.txt.
  • JSON strings: Double quotes must be escaped, like {\"key\": \"value\"}.
  • Console applications: Clear screen or move cursor with a carriage return (\r).

Hands-on: Real-world applications

Emulating Control keys

Ever wondered how Ctrl+C or Ctrl+Z looks like in Java strings? Well, wonder no more! It's achieved using their ASCII values such as \u0003 for Ctrl+C and \u001A for Ctrl+Z.

// Control keys can also join the party String ctrlKeys = "It was all going fine, then she pressed \u0003. The end. :( ";

Making valid JSON strings

In JSON serialization, escaping characters is crucial. For instance, "name": "O'Connor" can be represented as "name": "O\'Connor", else you'd have to face the wrath of invalid JSON.

Regular Expression quirks

In regex, escaping is paramount. The literal use of regex special characters like parentheses, periods, etc., is made possible by preceding them with \. For example, \. will search for a literal ..