Regular expressions (regex) might be the most love-hate thing in programming. Fans say "one regex line replaces 100 lines of code." Critics say "writing is fun, but editing is hell."
I fall somewhere in between. I don't think regex is particularly hard, but I also don't think you need to master every detail. My approach: learn a few core patterns, and use a tester for the complex stuff.
Basic 1: Character classes
Character classes use square brackets [] and match any single character inside them. [abc] matches a, b, or c. [a-z] matches all lowercase letters. [0-9] matches all digits.
Real scenario: extract all phone numbers from text. Chinese mobile numbers start with 1, second digit is 3-9, followed by 9 digits. Pattern: 1[3-9]\d{9}. I used this to extract phone numbers from a 1000-line log file in 5 seconds. Manually, it would have taken 30 minutes.
Basic 2: Quantifiers — how many times
* matches 0 or more times. + matches 1 or more times. ? matches 0 or 1 time. {n} matches exactly n times. {n,} matches at least n times. {n,m} matches n to m times.
Real scenario: extract all URLs from text. Pattern: https?://[^\s]+. The ? makes the "s" optional, so it matches both http:// and https://.
Basic 3: Anchors — matching positions
^ matches the start of a line. $ matches the end. \b matches a word boundary.
Real scenario: find all lines starting with "ERROR." In log analysis, this is the most common task. Pattern: ^ERROR.*. When I worked in DevOps, I used this daily on multi-GB log files. My colleague was manually scrolling through logs — eye strain guaranteed.
Basic 4: Groups and capturing
Parentheses () create groups. Matched content is "captured" and can be referenced as $1, $2, etc.
Real scenario: extract username and domain from an email address. Pattern: (\w+)@(\w+\.\w+). $1 is the username, $2 is the domain. This is especially useful in search-and-replace operations.
Test your regex
The best way to learn regex is to practice. Open our Regex Tester, enter your pattern and test text, click "Match," and see highlighted results with position details and capture groups.
My advice: don't try to learn all regex syntax at once. Master these four basics, then look up advanced patterns as needed. Practice makes perfect.