Regex Escape Characters: How to Match Dots, Asterisks, and More
Learn how to properly escape special characters in regular expressions. Master matching literal dots, asterisks, and other metacharacters with practical examples.
One of the most common challenges for regex beginners is understanding when and how to escape special characters. In regular expressions, certain characters have special meanings and need to be "escaped" to match them literally. This guide will teach you everything you need to know about regex escape characters.
Understanding Special Characters in Regex
What Are Special Characters?
Special characters (also called metacharacters) in regex are characters that perform special operations rather than matching themselves literally. They're the building blocks that give regex its pattern-matching power.
Complete List of Regex Special Characters
. ^ $ * + ? { } [ ] \ | ( )
These characters have special meanings:
.- Matches any single character (except newline)^- Matches the start of a string/line$- Matches the end of a string/line*- Matches zero or more occurrences+- Matches one or more occurrences?- Matches zero or one occurrence{and}- Define quantifiers[and]- Define character classes\- Escape character|- OR operator(and)- Define groups
The Escape Character: Backslash ()
The backslash \ is the escape character in regex. When placed before a special character, it tells the regex engine to treat that character as a literal rather than a metacharacter.
How Escaping Works
// Without escaping: "." matches any character
pattern: .
text: hello
match: "h" (first character)
// With escaping: "\." matches a literal dot
pattern: \.
text: hello
match: none (no dots in text)
pattern: \.
text: hello.world
match: "." (the literal dot)
Characters That Need Escaping
1. The Dot (.)
The dot is one of the most commonly escaped characters because it's used frequently in real-world text.
Escaped Dot Examples
// Match a decimal number
pattern: \d+\.\d+
text: The price is 19.99 dollars
match: "19.99"
// Match a file extension
pattern: \.[a-z]{2,4}$
text: document.pdf
match: ".pdf"
// Match an IP address
pattern: \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
text: 192.168.1.1
match: "192.168.1.1"
2. The Asterisk (*)
Asterisks are common in programming and text formatting.
Escaped Asterisk Examples
// Match a bold marker in Markdown
pattern: \*.*?\*
text: This is *bold* text
match: "*bold*"
// Match multiplication expression
pattern: \d+\s*\*\s*\d+
text: 2 * 3 = 6
match: "2 * 3"
// Match wildcard pattern
pattern: \*\.txt$
text: Important file: backup*.txt
match: "backup*.txt"
3. The Plus Sign (+)
Plus signs are used in URLs, phone numbers, and various formats.
Escaped Plus Sign Examples
// Match international phone format
pattern: \+\d{1,3}[- ]?\d{3}[- ]?\d{3}[- ]?\d{4}
text: Call me at +1 555 123 4567
match: "+1 555 123 4567"
// Match URL encoding
pattern: %[0-9A-F]{2}
text: Hello%20World%21
match: "%20" and "%21"
// Match C++ in text
pattern: C\+\+
text: I know C++ and Java
match: "C++"
4. The Question Mark (?)
Question marks appear in URLs, file queries, and various formats.
Escaped Question Mark Examples
// Match URL query parameters
pattern: \?.*$
text: https://example.com/page?id=123
match: "?id=123"
// Match file with version number
pattern: filename\.v\d+\?$
text: Check filename.v2?
match: "filename.v2?"
// Match uncertain text marker
pattern: \(.*?\?\)
text: Maybe (not sure?)
match: "(not sure?)"
5. The Caret (^)
Carets are used in email addresses, XOR operations, and other contexts.
Escaped Caret Examples
// Match email with caret
pattern: [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
text: user@domain^com
match: "user@domain" (stops at caret)
// To include caret in allowed characters:
pattern: [a-zA-Z0-9._%+-^]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
text: user@domain^com
match: "user@domain^com"
// Match XOR operation
pattern: \w+\s*\^\s*\w+
text: a ^ b
match: "a ^ b"
6. The Dollar Sign ($)
Dollar signs appear in currency amounts and variable names.
Escaped Dollar Sign Examples
// Match currency amount
pattern: \$\d+(?:\.\d{2})?
text: Price: $19.99
match: "$19.99"
// Match JavaScript variable reference
pattern: \$\w+
text: The $el element is selected
match: "$el"
// Match multiple dollar amounts
pattern: \$\d+(?:\.\d{2})?
text: Items: $5.00, $10.00, $15.00
matches: "$5.00", "$10.00", "$15.00"
7. Parentheses ( )
Parentheses are used for grouping and are very common in text.
Escaped Parentheses Examples
// Match phone number with parentheses
pattern: \(\d{3}\)\s*\d{3}-\d{4}
text: Call (555) 123-4567
match: "(555) 123-4567"
// Match mathematical expression
pattern: \([^)]+\)
text: Calculate (3 + 5) * 2
match: "(3 + 5)"
// Match parenthetical note
pattern: \(.*?\)
text: This is important (read carefully)
match: "(read carefully)"
8. Square Brackets [ ]
Brackets define character classes but also appear in text.
Escaped Square Brackets Examples
// Match array-like notation
pattern: \[[^\]]+\]
text: items[0], items[1]
matches: "[0]", "[1]"
// Match specific bracketed content
pattern: \[error\]
text: [error] File not found
match: "[error]"
// Match bracketed expression
pattern: \[[a-z]+\]
text: value[test]
match: "[test]"
9. Curly Braces { }
Curly braces define quantifiers but also appear in various formats.
Escaped Curly Braces Examples
// Match JSON-like structure
pattern: \{[^}]+\}
text: data: {name: "John"}
match: "{name: "John"}"
// Match placeholder
pattern: \{\w+\}
text: Replace {name} with actual name
match: "{name}"
// Match format string
pattern: \%[a-z]\{[^\}]+\}
text: Format: %d{4}-%m{2}
matches: "%d{4}", "%m{2}"
10. The Pipe (|)
Pipes are used as OR operators but also appear in text.
Escaped Pipe Examples
// Match pipe character in text
pattern: \w+\s*\|\s*\w+
text: key1 | key2 | key3
matches: "key1 | key2", "key2 | key3"
// Match piped command
pattern: cat\s+\S+\s*\|\s*grep\s+\S+
text: cat file.txt | grep error
match: "cat file.txt | grep error"
// Match vertical bar separator
pattern: \w+\|\w+
text: a|b|c|d
matches: "a|b", "b|c", "c|d"
Practical Scenarios and Examples
Scenario 1: Matching File Paths
// Match Windows file path
pattern: [A-Za-z]:\\[^\\]+\\[^\\]+
text: C:\Users\Documents\file.txt
match: "C:\Users\Documents"
// Better: Use raw strings in many languages
pattern: [A-Za-z]:\\[^\\]+(?:\\[^\\]+)*
text: C:\Users\Documents\Projects\file.txt
match: "C:\Users\Documents\Projects\file.txt"
Scenario 2: Parsing Code
// Match function call
pattern: \w+\([^)]*\)
text: result = calculate(5, 10, 15)
match: "calculate(5, 10, 15)"
// Match array access
pattern: \w+\[\d+\]
text: value = array[0]
match: "array[0]"
// Match object property
pattern: \w+\.\w+
text: obj.property
match: "obj.property"
Scenario 3: Extracting URLs
// Match URL with special characters
pattern: https?://[^\s/$.?#].[^\s]*$
text: Visit https://example.com/path?param=value
match: "https://example.com/path?param=value"
// Match URL with escaped characters
pattern: https?://(?:[\w-]+\.)+[\w-]+(?:/[\w-./?%&=]*)?
text: https://sub.example.com/page?x=1&y=2
match: "https://sub.example.com/page?x=1&y=2"
Scenario 4: Validating Mathematical Expressions
// Match simple multiplication
pattern: \d+\s*\*\s*\d+
text: 5 * 10 = 50
match: "5 * 10"
// Match division
pattern: \d+\s*/\s*\d+
text: 20 / 4 = 5
match: "20 / 4"
// Match complex expression
pattern: \(?:\d+\s*[\+\-\*\/]\s*\d+\)+
text: (5 + 3) * (10 - 2)
match: "(5 + 3) * (10 - 2)"
Escaping in Different Programming Languages
JavaScript
// In JavaScript, use double backslashes for string literals
const pattern = /\d+\.\d+/; // Use regex literal
const pattern = new RegExp("\\d+\\.\\d+"); // Use constructor
Python
# In Python, use raw strings with r prefix
import re
pattern = r"\d+\.\d+" # Raw string (recommended)
pattern = "\\d+\\.\\d+" # Regular string (needs double escape)
Java
// In Java, use double backslashes
String pattern = "\\d+\\.\\d+"; // Regular string
PHP
// In PHP, use double backslashes in strings
$pattern = '/\d+\.\d+/'; // Use single quotes
$pattern = "/\\d+\\.\\d+/"; // Use double quotes
Special Escape Sequences
Beyond escaping special characters, regex provides special escape sequences for common patterns:
Character Classes (Shorthands)
\d- Any digit[0-9]\D- Any non-digit[^0-9]\w- Any word character[a-zA-Z0-9_]\W- Any non-word character[^a-zA-Z0-9_]\s- Any whitespace character\S- Any non-whitespace character
Anchors
\b- Word boundary\B- Non-word boundary\A- Start of string\z- End of string
Other Special Escapes
\n- Newline\r- Carriage return\t- Tab\v- Vertical tab\f- Form feed
Common Mistakes to Avoid
Mistake 1: Forgetting to Escape in String Literals
// Wrong in JavaScript string
const pattern = "\d+\.\d+"; // \d becomes just 'd', \. becomes '.'
// Correct: Use regex literal or double escape
const pattern = /\d+\.\d+/;
const pattern = new RegExp("\\d+\\.\\d+");
Mistake 2: Escaping Non-Special Characters
// Unnecessary escaping (but usually harmless)
pattern: \a\p\p\l\e
text: apple
match: "apple"
// Better: Don't escape non-special characters
pattern: apple
Mistake 3. Mixing Up Escape Characters
// Wrong: Confusing regex escape with language escape
pattern: \n // This is regex newline
// In string literals, need to escape again
const pattern = "\\n"; // This matches actual newline in regex
Testing and Debugging
Use Visual Testing Tools
Use our interactive Regex Tester to verify your escape sequences:
- Enter your test text with special characters
- Try your pattern with and without escapes
- See exactly what matches
- Adjust until you get the right results
Step-by-Step Testing
// Test 1: Without escape
pattern: .
text: hello.world
match: "h" (any character)
// Test 2: With escape
pattern: \.
text: hello.world
match: "." (literal dot only)
// Test 3: Combined
pattern: \w+\.\w+
text: hello.world
match: "hello.world"
Best Practices
1. Use Raw Strings When Available
# Python: Use raw strings
pattern = r"\d+\.\d+" # Good
pattern = "\\d+\\.\\d+" # Hard to read
# JavaScript: Use regex literals
const pattern = /\d+\.\d+/; // Good
const pattern = new RegExp("\\d+\\.\\d+"); // Verbose
2. Escape Only When Necessary
Don't escape characters that don't have special meanings:
// Unnecessary
pattern: \a\b\c
// Cleaner
pattern: abc
3. Use Character Classes for Multiple Characters
// Instead of escaping multiple characters
pattern: \[|\]|\{|\}|\(|\)|\.
// Use character class
pattern: [\[\]\{\}\(\)\.]
4. Document Complex Patterns
// Complex pattern with comments (if supported)
pattern: (
https?:// # Protocol
[^\s/$.?#]. # Domain
[^\s]* # Path and query
)
Quick Reference Card
Character | Escaped | Meaning
----------|---------|----------------------------------------
. | \. | Literal dot (not any character)
* | \* | Literal asterisk (not zero or more)
+ | \+ | Literal plus (not one or more)
? | \? | Literal question mark (not zero or one)
^ | \^ | Literal caret (not start of line)
$ | \$ | Literal dollar sign (not end of line)
[ | \[ | Literal opening bracket
] | \] | Literal closing bracket
{ | \{ | Literal opening brace
} | \} | Literal closing brace
( | \( | Literal opening parenthesis
) | \) | Literal closing parenthesis
| | \| | Literal pipe (not OR)
\ | \\ | Literal backslash (always escape)
Conclusion
Understanding how and when to escape special characters is fundamental to mastering regular expressions. The key points to remember are:
- Escape special characters (
.*+?^$[]{}()|\) when you want to match them literally - Use the backslash
\as the escape character - Consider your programming language and how it handles escape sequences
- Test your patterns thoroughly with our interactive Regex Tester
- Use raw strings when available to make patterns more readable
With practice, escaping special characters will become second nature. Start with simple examples and gradually work your way up to more complex patterns. Remember: the key is to understand when a character has special meaning and when it should be treated literally.
Ready to practice? Try our interactive Regex Tester with the examples from this guide and experiment with different escape sequences!
About the Author
The Regex Master Team consists of experienced developers and technical writers dedicated to simplifying regular expressions for everyone. We ensure all patterns are rigorously tested and verified to provide accurate, production-ready solutions.
Try It: Regex Tester
Use our interactive regex tester to experiment with the patterns you learned in this article. Test your regular expressions in real-time and see immediate results.