🌐 English

Home › Guides

Practical regex patterns and what to watch for

Regular expressions are powerful for finding rules inside text, but trying to solve everything with one line often creates bigger problems. This guide collects patterns you will actually use and the traps around greedy matching, anchors and performance. If the syntax is new to you, read the basics guide first.

Number and date patterns

An integer is ^\d+$, and allowing a sign and decimals gives ^-?\d+(\.\d+)?$. Thousands separators need an explicit rule such as ^\d{1,3}(,\d{3})*$. The leading ^ and trailing $ mean the whole string must match.

The format 2024-01-05 can be checked for shape with ^\d{4}-\d{2}-\d{2}$. But 2024-13-45 passes too, so use the pattern for shape and check real calendar validity with date handling.

Cleaning whitespace and extracting parts

To collapse several spaces into one, find \s+ and replace it with a single space. Leading and trailing whitespace can be found with ^\s+|\s+$ and removed. Remember that line breaks count as \s too.

To pull out parts, use parenthesized groups. (\d{4})-(\d{2})-(\d{2}) gives year, month and day as separate groups. Named groups are easier to read later, and (?:...) groups without capturing.

The greedy matching trap

The repetition symbols * and + match as much as possible by default. Testing <.+> on <a>text</b> grabs everything from the first opening bracket to the last closing one. Adding ?, as in <.+?>, makes it match as little as possible.

A better approach is to exclude unwanted characters directly. <[^>]+> takes only characters that are not a closing bracket, so the intent is clear and it runs fast.

The limits of validation

Trying to validate a complex format such as an email address or phone number perfectly with one expression usually fails because there are too many rules. Use a regular expression as a first filter for clearly wrong input, and confirm correctness another way, such as sending a confirmation message.

Passing a format check also does not make a value safe. A pattern sees only the shape, not whether the content is dangerous.

Performance and how to test

Nested repetition such as (a+)+ can explode the number of attempts on a long non-matching input and appear to hang. Using such an expression on user input can cause an outage, so avoid putting a repetition inside a repetition.

When building an expression, prepare examples that should match and examples that should not, and test both. Pasting both kinds of sentences into the regex tester on this site reveals missed cases immediately.