Learn regular expressions · Lesson 13

Unicode

Most text isn’t ASCII. Names, addresses and messages have å, é, ß, 東京 and emoji in them, and a pattern written for English quietly misses them. This lesson is about matching text in any language.

Unicode properties: \p{…}

Every character in Unicode has properties: whether it’s a letter, a digit, punctuation, which script it belongs to. \p{…} matches a character with a property, and \P{…} one without.

  • \p{L} a letter, in any script; \p{Lu} an uppercase one, \p{Ll} lowercase
  • \p{N} a number, \p{Nd} a decimal digit
  • \p{P} punctuation, \p{S} a symbol, \p{Z} a separator
  • \p{Script=Greek}, \p{Script=Han} … a script

In JavaScript they need the u (or v) flag:

/\p{L}+/gu4 matches
naïve café, Straße 12, 東京
Try it in Dotstar →

Where \w+ would cut “naïve” in two, \p{L}+ matches runs of Unicode letters in any script. Combining marks (an accent written as a character of its own, below) are \p{M}, not letters, so to keep them in a word, include them: [\p{L}\p{M}]+.

/\p{Script=Greek}+/gu3 matches
alpha α, beta β, gamma γ
Try it in Dotstar →

What one character is

A “character” on the screen can be several things in memory. Unicode gives each character a number, a code point: é is U+00E9, 😄 U+1F604. JavaScript, Java and .NET store text as UTF-16, where a code point above U+FFFF takes two code units; without the u flag JavaScript’s regex works in code units, so . matches half an emoji. And what a reader sees as one character, a grapheme, can be several code points: é can also be written as e followed by a combining accent, U+0301, and 👍🏽 is a thumb and a skin tone.

\X matches one grapheme, whatever it’s made of, in the engines that have it.

Same text, different code points

Because é can be one code point or two, a pattern with é in it doesn’t match the other form: the two look identical and compare unequal. Text from different sources (a Mac’s file names, a form, a database) can come in either. The cure is to normalize the text before matching, usually to NFC, the composed form: text.normalize("NFC") in JavaScript, unicodedata.normalize("NFC", text) in Python.

Case beyond ASCII

With the i flag, which characters count as the same letter? For ASCII it’s simple. Beyond it, engines use Unicode’s case folding, which has its corners: ß and SS, the Turkish dotted and dotless i, the Kelvin sign K (U+212A), which folds to k. Engines handle one-to-many folds like ß → ss differently, so don’t rely on (?i)strasse matching “Straße”.