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

TokenDescription
(Start of capturing group
["']Character class — matches any one of: "'
)End of group
(?:Start of non-capturing group
(?!Start of negative lookahead assertion
\1Escaped 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)
\1Escaped 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

InputExpected
"hello world"Match
'single quotes'Match
no quotesNo Match
"escaped \"quote\""Match
"mismatched'No Match

Try It — Interactive Tester

//g
gimsuy

Match Highlighting(3 matches)

"hello world" 'single quotes' no quotes "escaped \"quote\"" "mismatched'

Matches & Capture Groups

#1"hello world"index 0
Group 1:"
#2'single quotes'index 14
Group 1:'
#3"escaped \"quote\""index 40
Group 1:"
Pattern: 27 charsFlags: gMatches: 3

Ctrl+Shift+C to copy regex

Customize this pattern →