Testing before you ship
A regular expression is easy to write and hard to be sure about. The failure mode is rarely a syntax error — it is a pattern that works on the three examples you tried and quietly mishandles the fourth. Seeing every match highlighted in place, against realistic input, is the fastest way to find that out.
The flags
- g — without it you get only the first match, which is the most common surprise.
- m — makes
^and$match at each line break rather than only at the start and end of the whole string. - s — lets
.match a newline. Without it,.stops at line ends, which breaks patterns meant to span lines. - i — case-insensitive matching.
Two things worth avoiding
The first is nested quantifiers. A pattern like (a+)+$ looks harmless and takes exponential time on input that almost matches — enough to freeze a browser tab or take down a server. If a pattern feels slow on a long string, that is usually why.
The second is parsing structured formats with regex. HTML, JSON and CSV all have nesting and quoting rules that regular expressions cannot express correctly. Use the JSON formatter or HTML beautifier instead — a real parser will handle the cases your pattern will not.