Lecture 10: Regular expressions
Overview
Burton Ma introduces POSIX extended regular expressions in Bash as a way to search for text patterns and validate strings, emphasizing that regex metacharacters often differ from Bash glob syntax. He explains anchors, character classes, quantifiers, grouping, and alternation, then applies them with `grep -E` to search filenames, source code, HTML, and word lists.
Key takeaways
- In Bash, `[[ string =~ regex ]]` checks for a matching substring by default; use `^` and `$` when the entire string must satisfy the pattern.
- Quoting changes regex interpretation: a quoted pattern can be treated as a literal string rather than as an expression with active metacharacters.
- For POSIX extended regular expressions, `*`, `+`, and `?` quantify the preceding atom as zero-or-more, one-or-more, and zero-or-one occurrences.
- Use parentheses to group repeated or alternative patterns, because `|` alternates between expressions and its scope can change the match substantially.
- `grep -E` searches file lines with extended regex syntax, while options such as `-n` add useful context like source-code line numbers.
- A pattern that finds intended matches can also capture unwanted ones; test regexes against counterexamples and consider whether regex is the right approach.
Chapters
- Regular expressions define text patterns for searching strings and validating input such as phone numbers or postal codes.
- Regex symbols such as `*`, `?`, and `[]` can mean different things than they do in Bash glob patterns.
- Burton Ma limits the lesson to core concepts, noting that regular expressions have many variants and can be difficult to write reliably.
- For Bash string conditions, the course uses `[[ ... ]]`; numeric conditions use `(( ... ))`.
- The `=~` operator tests whether the string on the left contains a match for the regular expression on the right.
- Anchors are needed when a match must cover the entire string rather than just a substring.
- Quoting a full regex can turn it into a literal string comparison, while quoting part of it makes that portion literal.
- Ordinary characters match themselves, so the pattern `A` searches for a literal uppercase A.
- Bash matching is case-sensitive: `hello` contains lowercase `h`, but not uppercase `H`.
- A sequence such as `and` matches only when those characters occur consecutively, not when they are separated within a word.
- The `test_re` helper script demonstrates whether a supplied string matches a supplied pattern.
- `^` anchors a pattern to the start of a string, while `$` anchors it to the end.
- Combining `^` and `$` with literal text, as in `^hy$`, requires an exact match for `hy`.
- The dot `.` matches any single character, so `^H..L$` matches a four-character string beginning with H and ending with L.
- Removing anchors changes an exact-string test into a search for a matching substring.
- A bracket expression such as `[aei]` matches one character from its listed set; `[a-z]` matches a lowercase letter.
- A caret at the start of a bracket expression, as in `[^aei]`, negates the set.
- Place a hyphen first in a bracket expression to match a literal hyphen alongside a range.
- Putting a metacharacter such as a period inside brackets, `[.]`, matches it literally; an unbracketed `.` matches any character.
- An atom can be a literal character, bracket expression, or parenthesized subexpression.
- `*` means zero or more occurrences, `+` means one or more, and `?` means zero or one.
- The anchored pattern `^[0-9]+$` matches strings containing one or more digits, including values with leading zeros.
- An optional sign can be added with `[+-]?`; the POSIX class `[[:digit:]]` can replace `[0-9]`.
- Brace quantifiers specify counts: `{2}` means exactly two occurrences, `{1,}` means one or more, and `{1,3}` means one through three.
- Parentheses group a pattern into one atom, so `(ABC)+` matches one or more consecutive `ABC` groups.
- The vertical bar `|` means alternation, matching either the expression before it or the expression after it.
- Parentheses control the scope of alternation, allowing patterns such as `^(19|20)[0-9][0-9]$` to match years from 1900 through 2099.
- `grep -E` searches file lines using POSIX extended regular expressions; without `-E`, grep uses basic regular-expression syntax.
- Piping `ls` output to `grep -E` finds filenames containing `zip`; `^zip` finds names starting with it, and `zip$` finds names ending with it.
- The `-n` option shows line numbers when searching source code, but searching for `for` alone also finds comments and unrelated text.
- A more selective Java loop pattern uses `for`, optional whitespace via `[[:blank:]]*`, and a literal opening parenthesis written as `[(]`.
- A grep pattern can locate HTML anchor tags by searching for the literal opening sequence `<a `.
- A word-list search can find five-letter words matching a structure such as any letter, `k`, any letter, then `s`.
- Burton Ma cautions that a regex can match unwanted text even when it finds the intended examples, and recommends testing patterns carefully.
- He points to further regex references, including examples for matching email addresses, and notes that regex is not always the best tool for a task.
Transcript excerpt
0:04 Okay, good morning everybody. Let's get started. >> Uh so if you look at the next notebook in the sequence, uh the next notebook in the sequence is actually the notebook called TR. Uh so TR is short for uh translate. Uh I'm going to skip over that notebook and come back to it um in the next lecture I think because the last question of your assignment um has you use something called a regular expression. So I think it's important that I show you how to uh work with regular expressions so that you can actually finish the assignment. All right. So what is a regular expression? So we'll start with a little quote here. Uh some people when confronted with a problem think I know I'll use regular expressions. Now they have two problems. Uh and so that's the
0:53 written by this um gentleman who runs this website called reax.info which not surprisingly is a website um that deals solely with regular expressions. So a regular expression um is like a mini language. Um so it lets you uh define uh it lets you define it's a language for defining patterns of text. um and they let you search text uh to see if that text contains something that matches um the given pattern. Now, we've seen some primitive pattern matching in bash, right? So, we've seen the star, the question mark, and the square brackets. Um regular expressions uh are much more sophisticated than bash's uh relatively primitive pattern matching.
1:43 Unfortunately, most regular expression um most versions of regular expressions use the same set of characters that bash uses for its glob patterns, right? So the star, the question mark, square brackets, these all have different meanings uh when you're talking about a regular expression. Uh so it's something you
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Burton Ma.