Regex Guide
Regex Guide with syntax, groups, quantifiers, flags, practical examples, debugging, performance, and a reliable Trexmi testing workflow.
Quick Tool
Test a regex against real input now
Start with Regex Tester or Regex Builder, then use the guide to understand syntax, character classes, groups, quantifiers, flags, replacement, extraction, debugging, and performance.
What is a regex and how does it work?
A regular expression, usually called a regex, describes a text pattern rather than one fixed value. The pattern cat matches those exact letters, while d+ matches one or more digits. A regex engine reads the expression, scans the input, and reports the parts that satisfy the pattern.
Regex is useful for log analysis, form validation, code refactoring, data cleanup, URL extraction, identifier parsing, and many other developer workflows. A focused expression can locate thousands of values in seconds, but an overly broad expression can produce false matches or expensive backtracking.
Regex engines are not identical. Trexmi server-side tools use PCRE-style behavior, while JavaScript, Python, Java, .NET, Go, and database systems support slightly different syntax. Always verify an important production expression in its destination environment. The PHP PCRE documentation and the MDN regex guide are useful external references.
How to use the Regex Tester
- Paste representative input that includes both values that should match and values that must not match.
- Enter the smallest useful pattern first, then add anchors, groups, alternation, or optional parts only when the basic match is correct.
- Choose the flags required by the use case and inspect every match and capture group. Verify important patterns in the final language or regex engine because syntax can differ.
- After matching is correct, move to Regex Replace when you need a transformation or Regex Extractor when you need to collect matching values from larger text.
Examples
ISO-style date shape
\d{4}-\d{2}-\d{2}This matches the numeric shape of a date. It does not prove that every matched calendar date actually exists, so keep syntax matching separate from business-rule validation.
Email-like extraction
[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}This is useful for finding common email-shaped text. A signup flow should still normalize the address and verify ownership rather than treating a regex match as proof that the mailbox is valid.
URL-like extraction
https?://[^\s<>"']+A focused pattern can extract URL-like text from logs or documents. Use a real URL parser when you need strict validation of complete URL syntax.
Debugging lab
Regex Debugging Lab
Use a small representative input for each pattern and include at least one string that must not match. The same pattern can behave differently across regex engines, flags, and APIs.
| Concept | Pattern / input | Expected result | Why |
|---|---|---|---|
| Greedy vs lazy | <.*> on <b>x</b><i>y</i> | Greedy: whole span; <.*?>: each shortest tag | A greedy quantifier expands as far as it can before backtracking; a lazy quantifier prefers the shortest successful match. |
| Capturing vs non-capturing | (cat|dog) vs (?:cat|dog) | Both match; only the first creates a numbered group | Use non-capturing groups when grouping is needed for precedence but downstream code does not need the captured text. |
| Named group | (?<year>\d{4})-(?<month>\d{2}) | 2026-10 → year=2026, month=10 | Names make extraction code easier to understand than relying on capture-group numbers. |
| Multiline anchors | ^ERROR on a multi-line log | Matches line starts only with multiline mode | Without the multiline flag, ^ and $ normally refer to the start and end of the entire input. |
| Unicode letters | \p{L}+ with Unicode mode | Matches words such as café and Київ | ASCII classes are not sufficient for multilingual text; Unicode property support depends on the engine and flags. |
| Positive lookahead | \d+(?= USD) | 42 from “42 USD” | A lookahead requires following text without consuming it as part of the match. |
| Replacement groups | Pattern: (\w+) (\w+); replacement: $2, $1 | Ada Lovelace → Lovelace, Ada | Test the match and capture order before using groups in a destructive search-and-replace operation. |
| Zero-length match | ^|$ on abc | Two zero-width matches | Patterns that can match zero characters need careful iteration logic or replacement code may behave unexpectedly. |
| Catastrophic backtracking | ^(a+)+$ against a very long aaaa…! | Near miss can become extremely slow | Nested ambiguous quantifiers can cause explosive backtracking in engines without protective optimizations. |
| Engine difference | Named groups / lookbehind / Unicode classes | Verify in the production engine | JavaScript, PCRE, Python, .NET, Java, RE2, and database regex dialects do not expose identical features or syntax. |
A practical regex test set
| Test | Purpose | Example |
|---|---|---|
| Positive example | Must match | A normal valid value |
| Negative example | Must not match | A clearly invalid value |
| Boundary example | Tests anchors and length | Shortest / longest allowed value |
| Near miss | Tests correctness and performance | Almost valid but fails at the end |
| Unicode / unusual input | Tests assumptions about character classes | Accents, Cyrillic, emoji, line breaks |
Check: For validation, extraction, and replacement, correctness includes the values that must not match. A pattern that matches the happy path but over-matches real data is still wrong.
Common use cases
Log analysis
Find IDs, status codes, paths, timestamps, or other repeated text shapes in large log samples without manually scanning every line.
Form validation
Use anchored patterns for narrow structural checks, then keep domain-specific rules and ownership verification outside the regex when they require more than text shape.
Data extraction
Capture named or numbered groups when downstream code needs separate values such as a prefix, date component, or identifier.
Search and replace
Test the match set first, then use capture groups in a replacement only after you have confirmed that the pattern does not select unintended text.
QA and cleanup
Positive and negative examples make regex useful for repeatable checks during content cleanup, migration, refactoring, and test preparation.
Advanced tips
Anchor full-value validators
An unanchored pattern can match a valid fragment inside an invalid value. Use beginning and end anchors when the entire input must conform.
Avoid ambiguous repetition
Nested quantifiers and overlapping alternatives can trigger expensive backtracking. Keep repetition specific and test long near-miss inputs.
Prefer named groups for structured results
Named groups make captured values easier to understand when a pattern extracts multiple fields that later code needs to process.
Respect engine differences
PCRE, JavaScript, Python, Java, .NET, Go, and database engines do not support exactly the same syntax or flags. Verify production patterns in the destination environment.
Use a parser for full grammars
JSON, XML, HTML, URLs, and programming languages have dedicated parsers. Regex is strongest when the target is a focused text pattern rather than a complete structured grammar.
Regex Guide to core building blocks
Literal characters
Most letters and digits match themselves. The expression error finds that exact sequence. Regex metacharacters such as ., *, +, ?, (, ), [, ], {, }, ^, $, and | must be escaped when you want their literal meaning.
Character classes
| Token | Meaning | Example |
|---|---|---|
d |
Digit | d{4} |
w |
Word character | w+ |
s |
Whitespace | s{2,} |
[A-Z] |
Uppercase ASCII letter | [A-Z]{2} |
[^,] |
Any character except comma | [^,]+ |
Anchors and boundaries
^ and $ anchor a pattern to the beginning and end of the input or line, depending on flags. b marks a word boundary. Anchors are essential when validating a complete value instead of searching inside larger text.
Regex quantifiers and repetition
Quantifiers control repetition. Use + for one or more, * for zero or more, ? for optional content, {3} for exactly three, and {2,5} for a bounded range. Greedy quantifiers consume as much as possible. Adding ? after a quantifier usually makes it reluctant.
d{4}-d{2}-d{2}
This pattern finds the numeric shape of an ISO-style date. It does not prove that every matched date exists on the calendar.
Warning: Nested quantifiers such as
(a+)+can trigger catastrophic backtracking on long input. Keep repetition specific and test worst-case data.
Capture groups, named groups, and alternation
Parentheses create groups. Numbered capture groups make portions of the match available separately. Named groups improve readability and make downstream processing easier:
(?<year>d{4})-(?<month>d{2})-(?<day>d{2})
Use (?:...) when grouping is needed without capturing. Alternation uses |, as in jpg|png|webp. Group alternatives carefully because operator precedence can broaden a regex unexpectedly.
Regex Guide to common flags
- g returns all matches instead of stopping after the first.
- i enables case-insensitive matching.
- m changes how line anchors behave in multiline input.
- s allows dot to match newline characters.
- u enables Unicode-aware processing where supported.
- x allows readable spacing and comments in PCRE-style patterns.
Practical regex examples
Email-like values
[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}
This catches common email-shaped values for extraction or basic checks. A production signup flow should also normalize the address and verify ownership.
URLs
https?://[^s<>"']+
This is useful for finding URL-like text. For strict URL validation, use a URL parser because complete URL syntax is too complex for one short universal expression.
UUID values
b[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}b
Order identifiers
b(?<prefix>[A-Z]{2,5})-(?<number>d{3,10})b
A reliable Regex Guide workflow
- Collect representative positive examples.
- Add negative examples that must not match.
- Build the smallest useful expression.
- Test flags, boundaries, and capture groups.
- Use replacement or extraction only after matching is correct.
- Test long and adversarial input for performance problems.
- Verify the final expression in the destination language.
Start with Regex Builder for common patterns. Inspect matching behavior in Regex Tester PRO. Transform matches with Regex Replace, and collect matching values with Regex Extractor. These internal tools turn the Regex Guide into a practical workflow rather than a theory-only article.
Common regex mistakes
Using an unanchored validator
A pattern may find a valid fragment inside an invalid value. Add ^ and $ when the whole input must conform.
Overusing dot-star
.* is convenient but often captures too much. Prefer a specific character class and a clear delimiter.
Forgetting to escape user input
Text inserted dynamically into a regex can change the pattern. Escape untrusted literal input before compilation.
Ignoring Unicode
ASCII-only character classes may reject valid international text. Use Unicode mode and engine-appropriate properties where multilingual input is expected.
Regex performance and safety
Performance depends on pattern structure, engine behavior, and input length. Ambiguous alternatives and nested repetition can make execution time grow rapidly. Limit input size, cap the number of returned matches, and avoid executing untrusted expressions against sensitive production data.
Pro tip: A fast result on one short sample does not prove that a regex is safe. Test long strings that almost match, because near-misses often reveal backtracking problems.
When not to use regex
Use a dedicated parser for JSON, XML, HTML, URLs, email delivery rules, programming languages, and other structured formats when correctness matters. Regex is excellent for focused text patterns, but it is not always the safest replacement for a grammar-aware parser.
Regex Guide summary
A dependable regex starts with a narrow goal, realistic examples, clear boundaries, and careful testing. Use named groups when results need structure, choose flags deliberately, avoid ambiguous repetition, and verify the final expression in the target engine. Trexmi tools help separate pattern creation, testing, replacement, and extraction so each step remains easy to inspect.
Practice what you learned
Related Trexmi tools
Open a focused workspace and test the patterns from this guide.Clear answers
Frequently asked questions
What is a regex?+
A regex is a pattern language used to locate, validate, extract, or replace text.
Which regex engine does Trexmi use?+
Trexmi server-side regex tools use PCRE-style behavior. Verify important expressions in the final destination environment.
Can regex validate every email address?+
A practical regex can catch common shapes, but complete validation should also use normalization and ownership verification.
Why is my regex slow?+
Nested quantifiers, ambiguous alternatives, and large input can cause expensive backtracking. Simplify the pattern and constrain input.
Should I use regex to parse JSON or HTML?+
Use a dedicated parser when correctness matters. Regex is better for focused text patterns than full structured grammars.
How should beginners test a regex?+
Start with positive and negative examples, test one feature at a time, inspect capture groups, and verify the final pattern in the destination engine.