Regex to Match Quoted Strings
Match single-quoted or double-quoted strings with this regex pattern. Correctly handles escaped quote characters within strings. Free regex tester.
Regular Expression
/(["'])(?:(?!\1|\\).|\\.)*\1/g
Token Breakdown
| Token | Description |
|---|---|
| ( | Start of capturing group |
| ["'] | Character class — matches any one of: "' |
| ) | End of group |
| (?: | Start of non-capturing group |
| (?! | Start of negative lookahead assertion |
| \1 | Escaped character '1' |
| | | Alternation — matches the expression before OR after the pipe |
| \\ | Escaped character '\' |
| ) | End of group |
| . | Matches any character except newline (unless dotAll flag is set) |
| | | Alternation — matches the expression before OR after the pipe |
| \\ | Escaped character '\' |
| . | Matches any character except newline (unless dotAll flag is set) |
| ) | End of group |
| * | Matches the preceding element zero or more times (greedy) |
| \1 | Escaped character '1' |
Detailed Explanation
This regex matches strings enclosed in either single or double quotes, correctly handling escaped characters. Here is the token-by-token breakdown:
(["']) — A capturing group matching either a double quote or a single quote. This captures the opening quote character so we can reference it later to ensure the closing quote matches.
(?: — Opens a non-capturing group for the string content, repeated zero or more times.
(?!\1|\). — A negative lookahead followed by any character. The lookahead (?!\1|\) asserts that the next character is neither the opening quote (referenced by \1 backreference) nor a backslash. If the assertion passes, the dot matches that character. This handles normal characters within the string.
| — Alternation within the non-capturing group.
\. — Matches a backslash followed by any character. This handles escape sequences like ", ', \n, \t, etc. By consuming both the backslash and the following character together, escaped quotes are not mistaken for closing quotes.
)* — Closes the non-capturing group and repeats zero or more times.
\1 — A backreference matching the same quote character that was captured in group 1. If the string opened with a double quote, it must close with a double quote, and vice versa.
The g flag enables global matching. This pattern is commonly used in syntax highlighters, code parsers, and text extraction tools. It correctly handles strings like "hello world", 'it's fine', and "escaped "quotes"".
Example Test Strings
| Input | Expected |
|---|---|
| "hello world" | Match |
| 'single quotes' | Match |
| no quotes | No Match |
| "escaped \"quote\"" | Match |
| "mismatched' | No Match |
Try It — Interactive Tester
Match Highlighting(3 matches)
Matches & Capture Groups
27 charsFlags: gMatches: 3Ctrl+Shift+C to copy regex