Web Analytics

Regular Expressions

Advanced~30 min read

Master regex with grep -E and sed -E to search, extract, and transform text streams efficiently.

grep -E and sed -E

Output
Click Run to execute your code
Output
Click Run to execute your code
Note: grep -E enables EREs; grep -P (PCRE) may not be available everywhere.
Pro Tip: Use -o to extract only matches and -n to show line numbers.
Caution: Some shells alias grep; prefer explicit flags (-E, -F) for clarity.

Common Mistakes

1) Forgetting to escape backslashes

# Wrong (\d is not ERE)
grep -E '\\d+' file
# Correct (use [0-9] or -P if available)
grep -E '[0-9]+' file

2) Greedy patterns in sed

# Over-matching
echo 'a[b]c[d]e' | sed -E 's/\[[^]]*\]/X/g'

Exercise: Mask Emails

Task: Read lines from stdin and replace the username of emails with ***, keeping the domain.

Output
Click Run to execute your code
Show Solution
sed -E 's/[A-Za-z0-9._%+-]+@/***@/g'

Summary

  • Use -E for ERE patterns.
  • Extract with -o and transform with sed -E.
  • Escape carefully; prefer character classes.

What's Next?

Edit streams powerfully with sed.