A Beginner’s Guide to Regular Expressions (With Examples That Actually Work)
Regular expressions look like random punctuation. A pattern like d+ or ^[A-Za-z]+$ can seem unreadable at first, but it is simply a compact way to describe a text pattern. Regular expressions, often called regex, let you search, validate, and replace text that follows a rule, rather than one exact string. You can find all numbers in a document, check whether an input looks like a date, or clean up messy spacing. This beginner guide explains the building blocks in plain language, shows examples that actually work, and explains when not to use regex.
What Is a Regular Expression
A regular expression is a pattern that describes a set of strings. A search engine for exact text looks for one literal string, such as the word order. A regex search looks for a shape, such as one or more digits, or a word at the start of a line. Most programming languages, editors, and command-line tools support regex, although small details differ between them. The core ideas are the same across languages: literal characters match themselves, special characters describe classes and repetition, and anchors describe position.
Regex is powerful because it is flexible. You can describe a date as four digits, a hyphen, two digits, a hyphen, and two digits. You can describe a product code as letters followed by numbers. You can find extra spaces and replace them with a single space. That flexibility also makes regex easy to misuse. A pattern that is too broad will match things you did not intend. A pattern that is too strict will miss valid input. The solution is to start small, test each piece, and build up gradually.
The Core Building Blocks
Literal characters. Most letters and digits match themselves. The pattern cat matches the letters c, a, and t in that order. It will match cat inside the word catalog as well, unless you add boundaries.
d for digits. The shorthand d matches any single digit from 0 to 9. The pattern d+ means one or more digits. The plus sign means one or more of the previous item. So d+ will match 7, 123, and 2024. It will not match an empty string, because plus requires at least one digit. If you want zero or more, use a star: d* matches zero or more digits, including an empty match. If you want zero or one, use a question mark: d? matches zero or one digit.
Dot. A dot matches any single character except a line break, in most default settings. The pattern a.c matches abc, a1c, and a c. It does not mean a literal dot. To match a literal dot, escape it with a backslash: . That distinction matters for file names, decimal numbers, and domain names.
Character classes. Square brackets define a set of characters. The pattern [abc] matches a single a, b, or c. The pattern [0-9] matches a single digit. The pattern [A-Za-z] matches a single letter. A caret inside brackets negates the set. The pattern [^0-9] matches a single character that is not a digit. Character classes are useful when you need a specific set and do not want to list every option separately.
Quantifiers. Quantifiers say how many times the previous item may repeat. Star means zero or more. Plus means one or more. Question mark means zero or one. Curly braces give an exact count or range. The pattern d{4} means exactly four digits. The pattern d{2,4} means two to four digits. The pattern d{3,} means three or more digits. Quantifiers are greedy by default, which means they try to match as much as possible. That can surprise beginners when a pattern matches more text than expected.
Anchors. The caret ^ matches the start of a string or line, depending on settings. The dollar sign $ matches the end of a string or line. The pattern ^d+$ means the whole string must be one or more digits. Without anchors, d+ would match the digits inside abc123def. With anchors, it will only match a string that is entirely digits. Anchors are essential for validation. If you want to check that an input is a number, anchor the pattern. Otherwise, you are only checking that it contains a number somewhere.
Groups and alternation. Parentheses group parts of a pattern. The pattern (cat|dog) matches cat or dog. The vertical bar means or. Groups also let you apply a quantifier to several characters at once. The pattern (ab)+ matches ab, abab, and ababab. Groups can capture matched text so you can reuse it in a replacement, depending on your tool.
How to Build and Test a Pattern
Step 1: Write down examples that should match
Before writing regex, list a few strings that should match and a few that should not. If you want to match order numbers, your yes list might include Order 123 and Order 42. Your no list might include Order, Order ABC, and 123 without the word Order. Examples keep you honest.
Step 2: Start with the simplest pattern
Start with a literal pattern, then add one feature at a time. For order numbers, start with Order, then add a space, then add digits: Order d+. Test after each step. If you add too much at once, you will not know which part failed.
Step 3: Test with real data
Test on real examples, not just the one case you had in mind. Include edge cases: empty input, extra spaces, leading zeros, uppercase and lowercase, and longer strings. Use a regex tester or your editor search with sample text. Check both matches and non-matches. A pattern that matches everything is not useful.
Step 4: Anchor when you validate
If you are validating an entire input, use ^ at the start and $ at the end. If you are searching inside a longer document, leave anchors out. Know which task you are doing. Mixing them up is a common source of bugs.
Step 5: Keep patterns readable
Regex is hard to read. Add comments in code, give the pattern a clear variable name, and explain what it is meant to match. If a pattern is long, break the problem into steps or use a simpler method. Readable code is more important than a clever one-line pattern.
Worked Example: Order Numbers and Dates
Suppose you have a short text: Order 123 was placed on 2024-05-06. Order 45 was placed on 2024-05-07. You want to find the order numbers and the dates.
To find order numbers, use the pattern Order d+. In the first sentence, it matches Order 123. In the second, it matches Order 45. It does not match Order on its own, because d+ requires at least one digit. It does not match a date, because the word Order is required first. If you only want the digits, you can use a group: Order (d+). The group captures 123 and 45. In many tools, you can replace Order (d+) with Order #$1 to produce Order #123 and Order #45. The $1 refers to the first group.
To find dates in the form year-month-day, use the pattern d{4}-d{2}-d{2}. In the example, it matches 2024-05-06 and 2024-05-07. It requires four digits, a hyphen, two digits, a hyphen, and two digits. It will also match 9999-99-99, which is not a real date, because regex checks shape, not calendar validity. If you need to check that a date is real, parse it with a date library after the regex finds the shape. Regex is good for finding the shape. A date parser is good for checking whether the date exists.
To validate that an entire input is a date, anchor the pattern: ^d{4}-d{2}-d{2}$. Now the input 2024-05-06 matches, but the input Date: 2024-05-06 does not, because the extra text breaks the anchors. That is the correct behaviour for validation. For searching inside a document, use the unanchored version.
To find a number at the start of a line, use ^d+. To find a number at the end of a line, use d+$. To match a word like cat as a whole word, use word boundaries in tools that support them, or combine anchors and spaces carefully. Test each version on your sample text before using it in code.
Common Mistakes
Forgetting to escape a dot is a classic mistake. The pattern 1.5 will match 1×5 as well as 1.5, because the dot matches any character. Use 1.5 when you mean a literal dot. Another mistake is using . * too freely. The pattern .* matches almost anything, including an empty string. It can swallow more text than you expect, especially when combined with greedy matching. Be specific. Use d+ for digits, [A-Za-z]+ for letters, and s+ for whitespace when that is what you mean.
Case sensitivity is another trap. By default, regex is usually case-sensitive, so cat does not match Cat. If you need case-insensitive matching, enable that option in your tool or language, or include both cases in a character class. Also watch out for different regex flavours. A pattern that works in one language may need small changes in another, especially for features like named groups, lookarounds, and escaping rules. Always test in the environment where the pattern will run.
Limitations: Regex Is Not for HTML Parsing
Regex is not a good tool for parsing HTML. HTML is nested, flexible, and often messy. Tags can have attributes in any order, can span lines, can be nested, and can contain comments and scripts. A regex that works for one simple page will break on the next page. For HTML, use a proper parser or a library that understands the document structure. The same rule applies to other nested formats like JSON and XML. Use a parser for structure, and use regex only for simple text patterns inside the values once the structure has been handled.
Regex is also not a good tool for validating complex formats on its own. Email addresses, URLs, and phone numbers have rules that are more complex than a simple pattern suggests. A regex can check a basic shape, but a dedicated validator or library is more reliable for real validation. Use regex for a first check, then use a proper validator for the final decision.
FAQ
What does d+ mean? It means one or more digits. The d matches a single digit from 0 to 9, and the plus sign means one or more of the previous item. So d+ matches 7, 123, and 2024.
What do ^ and $ do? The caret ^ anchors a pattern to the start of a string or line, and the dollar sign $ anchors it to the end. The pattern ^d+$ only matches a string that is entirely digits.
What is the difference between * + and ? Star means zero or more, plus means one or more, and question mark means zero or one. Use plus when you need at least one, star when empty is allowed, and question mark when the item is optional.
Should I use regex to parse HTML? No. HTML is nested and irregular, so regex will break on real pages. Use an HTML parser for HTML, and use regex only for simple text patterns.
Regular expressions become manageable when you learn a few building blocks and test each pattern with real examples. Start with literals, add d+, character classes, quantifiers, and anchors one at a time, and check both matches and non-matches. Use worked examples like Order 123 and 2024-05-06 to confirm your pattern does what you expect. Keep patterns readable, and choose a proper parser when the data has nested structure. With that approach, regex becomes a practical tool for searching, validating, and cleaning text.
Try a Tool
Free, in your browser — no sign-up.
Related Articles
How to Format XML So It Is Easy to Read
Learn how to format XML so it is easy to read: consistent indentation, one element per line, matched tags, unchanged data, and…
Read article →How to Build a Query String Without Breaking Your Link
Build a query string without breaking your link. Learn ?key=value, the & separator, encoding, a worked example, and why secrets stay out…
Read article →How to Convert Base64 Back to an Image
Learn how to convert Base64 back to an image, read a data URI, decode a 1 by 1 PNG example, check the…
Read article →