Regular expressions in depth
A regular expression is a tiny language for describing text. This lesson builds the vocabulary step by step — characters, classes, quantifiers, anchors, groups, replacing, splitting and validating.
What you will learn#
- the building blocks of a pattern,
- finding, replacing and splitting,
- groups and named groups,
- greedy and lazy matching,
- validating input,
- escaping text that is not a pattern.
Why learn them#
Whenever a job says "find the part of the text that looks like...", a regular expression does it in one line: phone numbers, dates, e-mails, log lines, codes. The same patterns work in every language, so what you learn here is useful everywhere.
The program#
# regular expressions in depth - patterns, groups, replace, split, validation
load "dotnet.ring"
using {
"System"
"System.Text.RegularExpressions"
}
func main
cText = "Ann: 555-0101, Bob: 555-0199, Cy: 555-0123 (call after 18:30 on 2024-05-17)"
# 1. Literal text matches itself
? "1. 'Bob' found? : " + new Regex("Bob").IsMatch(cText)
# 2. Character classes: \d a digit, \w a letter/digit/underscore, \s a space, [abc] one of these, . any character
? "2. First number : " + new Regex("\d+").Match(cText).Value
# 3. Quantifiers: + one or more, * zero or more, ? zero or one, {3} exactly three, {2,4} two to four
oPhone = new Regex("\d{3}-\d{4}")
oMatches = oPhone.Matches(cText)
? "3. Phone numbers : " + oMatches.Count + ", the first is " + oMatches.Item(0).Value
# 4. Anchors: ^ start, $ end, \b the edge of a word
? "4. Starts with 'Ann'? : " + new Regex("^Ann").IsMatch(cText) + ", ends with ')'? " + new Regex("\)$").IsMatch(cText)
# 5. Groups: parentheses capture parts. Named groups: (?<name>...)
oDate = new Regex("(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})").Match(cText)
? "5. Date parts : year " + oDate.Groups.Item("year").Value + ", month " + oDate.Groups.Item("month").Value + ", day " + oDate.Groups.Item("day").Value
# 6. Alternation: | means "or"
oNames = new Regex("Ann|Cy").Matches(cText)
? "6. Ann or Cy found : " + oNames.Count + " times"
# 7. Replace, also with the captured groups ($1, $2...) - here the date is turned around
? "7. Date turned around : " + new Regex("(\d{4})-(\d{2})-(\d{2})").Replace([ :input = cText, :replacement = "$3/$2/$1" ])
# 8. Split on a pattern: here on a comma and spaces
aParts = new Regex(",\s*").Split("one,two, three,four").toList()
? "8. Split into : " + len(aParts) + " parts, the third is '" + aParts[3] + "'"
# 9. Greedy and lazy: .* takes as much as it can, .*? as little
cHtml = "<b>bold</b> and <i>italic</i>"
? "9. Greedy : " + new Regex("<.*>").Match(cHtml).Value
? " Lazy : " + new Regex("<.*?>").Match(cHtml).Value
# 10. Options: ignore the case of the letters
? "10. 'BOB' ignoring case : " + (new Regex).@New([ :pattern = "BOB", :options = "IgnoreCase" ]).IsMatch(cText)
# 11. Validation: the whole text must match. ^ and $ make it all or nothing
? nl + "11. Is it a valid time (HH:MM)?"
for cTry in ["18:30","7:5","23:59","24:00"]
? " " + cTry + " -> " + new Regex("^([01]\d|2[0-3]):[0-5]\d$").IsMatch(cTry)
next
# 12. Special characters in your own text must be escaped
cUser = "a.b*c"
? nl + "12. Escaped text : " + new Regex("x").Escape(cUser)
? " Matches itself : " + new Regex(new Regex("x").Escape(cUser)).IsMatch("xx a.b*c yy")1. 'Bob' found? : 1
2. First number : 555
3. Phone numbers : 3, the first is 555-0101
4. Starts with 'Ann'? : 1, ends with ')'? 1
5. Date parts : year 2024, month 05, day 17
6. Ann or Cy found : 2 times
7. Date turned around : Ann: 555-0101, Bob: 555-0199, Cy: 555-0123 (call after 18:30 on 17/05/2024)
8. Split into : 4 parts, the third is 'three'
9. Greedy : <b>bold</b> and <i>italic</i>
Lazy : <b>
10. 'BOB' ignoring case : 1
11. Is it a valid time (HH:MM)?
18:30 -> 1
7:5 -> 0
23:59 -> 1
24:00 -> 0
12. Escaped text : a\.b\*c
Matches itself : 1The building blocks#
| Pattern | Matches | Example |
|---|---|---|
abc | exactly those letters | Bob |
. | any one character | b.b finds bob, bab |
\d \w \s | a digit, a letter/digit/underscore, a space | \d+ finds 555 |
[abc] [a-z] [^0-9] | one of these, a range, not these | [A-Z] |
+ * ? | one or more, zero or more, zero or one | \d+ |
{3} {2,4} | exactly three, two to four | \d{3}-\d{4} |
^ $ | the start, the end of the text | ^Ann |
\b | the edge of a word | \bcat\b |
a|b | a or b | Ann|Cy |
( ) | a group | (ab)+ |
(?<name> ) | a named group | (?<year>\d{4}) |
How the program uses them#
IsMatchanswers yes or no (step 1).Match(text).Valueis the first match,Matches(text)finds all of them: useCountandItem(i)(steps 2, 3).- Groups pick parts of a match:
Groups.Item("year").Value. The pattern(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})gives the three numbers of a date (step 5). - Alternation
Ann|Cyfinds either name (step 6). - Replace can use the groups in the replacement text (
$1,$2,$3): turning2024-05-17into17/05/2024is one call (step 7). - Split cuts a text at every match of the pattern:
,\s*is "a comma and any spaces" (step 8).
Greedy or lazy#
<.*> takes as much as possible: from the first < to the last >, the whole <b>bold</b> and <i>italic</i>. Adding ? (<.*?>) makes it take as little as possible: just <b>. When a pattern matches too much, try the lazy form.
Options#
Options change how a pattern behaves. They are enums, so in Ring they are texts: dnNew("Regex",[ :pattern = "BOB", :options = "IgnoreCase" ]). Others: Multiline, Singleline, Compiled (faster for patterns used many times).
Validation#
To check that the whole text has a shape, anchor the pattern: ^([01]\d|2[0-3]):[0-5]\d$ accepts 18:30 and 23:59 but not 7:5 or 24:00. Without ^ and $, IsMatch only asks whether the pattern occurs somewhere in the text.
Escaping#
Characters such as . * + ? ( [ \ have a meaning in a pattern. If you want to search for a text that a user typed, escape it first: Regex.Escape("a.b*c") gives a\.b\*c, which matches exactly a.b*c.
Good habits#
- Build a pattern in small steps and test each step.
- Put a pattern with comments in a variable with a clear name.
- Prefer a simple pattern plus some code over one unreadable pattern.
- Never use a regex to parse a language with nesting (HTML, JSON): use a parser (the tutorial JSON and XML).
What you learned#
- classes, quantifiers, anchors, groups, alternation,
IsMatch,Match,Matches,Replace,Split,- greedy vs lazy,
- anchored patterns for validation,
Escapefor user text.
Exercises#
- Write a pattern for a Ring variable name that starts with
norcfollowed by a capital letter (nCount,cName) and find them all in a source file. - Validate a simple e-mail address and test it with five good and five bad examples.
- Replace every run of spaces and tabs in a text by a single space.
- Extract all
#hashtagsfrom a sentence.