Lesson 10.2: Repetition, groups and alternatives
Quantifiers * + ? and {n,m}, basic versus extended regular expressions (grep and grep -E), grouping with parentheses, alternatives with |, word boundaries, and pulling matches out of text with grep -o: dates, e-mail addresses and IP addresses.
19 min
You will learn to
- Repeat a character or group with * + ? {n} {n,m}
- Explain the difference between BRE and ERE
- Group with ( ) and choose with |
- Match whole words with \< \> or \b
- Extract dates, e-mail addresses and IP addresses with grep -oE
Key terms
- Quantifier
- Says how many times the item before it may repeat: * zero or more, + one or more, ? zero or one, {n} exactly n, {n,} n or more, {n,m} between n and m.
- BRE and ERE
- Basic (grep, sed) and Extended (grep -E, sed -E, awk) regular expressions. Same ideas; in BRE + ? { } ( ) | need a backslash to be operators.
- Group ( )
- Treats several items as one, so a quantifier or | applies to all of them. Groups are also remembered for back-references (lesson 10.3).
- Alternation |
- Either the part on the left or the part on the right.
- Greedy matching
- A quantifier takes as much as it can: in 'a,b,c', ',.*,' matches ',b,' only because there's no later comma; .* would run to the last one.
- Word boundary
- \< and \> (GNU) or \b mark where a word starts or ends; a word is letters, digits and _.
- grep -o
- Prints each match on its own line instead of the whole line. Combined with sort | uniq -c it turns a log into statistics.
← Regular expressions: characters, classes and anchors · All lessons · Cleaning data with regular expressions in sed and awk →