Classical NLPNLP 01
Regular Expressions
A regular expression is a small pattern language for finding text. Before machine learning, most information extraction in NLP was done this way: hand-written patterns for doses, dates, measurements and identifiers. Pick an example or write your own; the pattern is explained piece by piece below. The abstract is fictional, with realistic details.
Text
edit text
Pattern explained
Cheat sheet click a row to try its example
| rule | meaning | try |
|---|---|---|
. | any character except a newline | C..D |
\d | a digit 0–9 | \d\d\d |
\w | an ASCII letter, digit or _ (not µ or é) | \w+@\w+ |
\s | whitespace | \d+\smmHg |
\b | word boundary (matches no character) | \bCI\b |
[abc] | one of a, b or c | [Pp]lacebo |
[^abc] | anything except a, b or c | \([^)]+\) |
[A-Z] | a range of characters | [A-Z]{3,}\d* |
* | previous item 0 or more times | \d+\.\d* |
+ | previous item 1 or more times | \d+ |
? | previous item optional | [Pp]\s?[<=] |
{n,m} | between n and m times | \d{4,} |
+? | lazy: as few as possible | \(.+?\) |
^ $ | start / end of a line (with m) | ^\w+: |
a|b | a or b | placebo|tiotropium |
( ) | capture group | (\d+)/(\d+) mmHg |
(?: ) | group without capturing | 18 (?:mcg|µg) |
\. | a literal dot (\ escapes special characters) | \d+\.\d+ |
Matches and capture groups
Background
Regular expressions come from the mathematics of automata: Stephen Kleene described “regular events” in 1956, and Ken Thompson turned them into a practical search tool in 1968, building them into the text editors that later gave Unix its grep command. This page uses JavaScript’s regular expressions, which add conveniences such as \d and lookahead to that original notation.
In practice
Hand-written patterns are still widely used in clinical and research NLP for well-formed items such as doses, dates, lab values and trial IDs. They are transparent and need no training data, but brittle: every variation (a missing space, “mcg” instead of “µg”, a new date format) needs another rule, and they match form rather than meaning, as the dose example shows. Even the shorthand is narrower than it looks: in JavaScript, \w covers only the ASCII letters, digits and underscore, so it does not match “µ” or “é”, and \w+@\w+ finds only moreau@hospital in the address above, because neither the dot in “j.moreau” nor the one before “example” is a word character.
References
- Kleene, S. C. (1956). Representation of events in nerve nets and finite automata. In C. E. Shannon & J. McCarthy (Eds.), Automata Studies (pp. 3–42). Princeton University Press. doi.org/10.1515/9781400882618-002
- Thompson, K. (1968). Regular expression search algorithm. Communications of the ACM, 11(6), 419–422. doi.org/10.1145/363347.363387
- MDN Web Docs. Regular expressions (JavaScript guide). developer.mozilla.org