Regex works on regex101 but not in code: backslash escaping
Regex matches on regex101 but not in PHP, C++, Splunk rex or PowerShell? Which backslashes to double, which engine to pick, and what else to check.
TroubleshootingUpdated 6 min read
On this page
You pasted a pattern into regex101, it matched, and the same pattern in your code does nothing. Splunk users often see this as:
Error in 'rex' command: Encountered the following error while compiling the regex ''(?<MyResult>[^'\\]+\\[^\\]+)'\s+\(': Regex: missing terminating ] for character class.People on programming forums report the same pattern in PHP preg_replace, C++ regex_match and PowerShell scripts. The usual replies are "you need 4 backslashes, not 2" and "use a single-quoted or raw string."
Why it happens
Causes, most common first:
- String-literal escaping. Code holds the pattern inside a string, and the string has its own escape rules. Each layer between your keyboard and the engine can consume backslashes.
- Wrong matching mode. regex101 finds a match anywhere in the text. Some functions, such as C++
std::regex_match, must match the whole string. - Missing delimiters or flags. PHP needs delimiters, and regex101's global flag is not a code flag.
- A different engine. regex101 has a flavor selector. Your host may use another flavor with different features.
- Different text. The text your code receives is not the text you tested (line endings, invisible characters, HTML after JavaScript ran).
- Interpolation in the replacement. Double-quoted strings can swallow
$1.
Backslash escaping: the same regex in each language
Take a pattern that regex101 shows as ^(\d+)\\(\w+)$. It matches digits, one literal backslash, then word characters.
| Host | String style | What you type | Notes |
|---|---|---|---|
| PHP | Single quotes | '/^(\d+)\\\\(\w+)$/' | \\ collapses to \, so a literal backslash needs 4. \d and \w pass through. |
| PHP | Double quotes | "/^(\\d+)\\\\(\\w+)$/" | Double every backslash. $name is also interpolated. |
| C++ | Normal literal | "^(\\d+)\\\\(\\w+)$" | Double every backslash. A lone \d is an unknown escape sequence. |
| C++ | Raw literal | R"(^(\d+)\\(\w+)$)" | Same as regex101. |
| PowerShell | Single quotes | '^(\d+)\\(\w+)$' | No change. Backslash is not an escape character. |
A normal C++ or PHP double-quoted string is a full layer, so you double. PHP single quotes only collapse \\ and \'. A C++ raw string or a PowerShell single-quoted string adds no backslash layer.
Fix 1: Double the backslashes, or use a raw string
Symptom: the pattern never matches in code, matches the wrong thing, or the compiler warns about an unknown escape sequence.
// regex101 shows: ^(\d+)\\(\w+)$
$pattern = '/^(\d+)\\\\(\w+)$/';
preg_match($pattern, $text, $m);#include <regex>
#include <string>
std::string text = "42\\alice"; // the text holds one backslash
std::regex re(R"(^(\d+)\\(\w+)$)"); // raw string: same as regex101
std::smatch m;
bool found = std::regex_search(text, m, re);$text = '42\alice'
$text -match '^(\d+)\\(\w+)$'
$Matches[1]- Get the pattern working on its own against a sample of your real text.
- Pick the string style. Prefer a raw string or single quotes, because you then change little or nothing.
- If you must use an escaped literal, double every backslash.
- Print the string at run time (
echo,std::cout,Write-Output) and compare it with regex101. If they differ, a layer changed something.
Fix 2: Splunk rex and "missing terminating ]"
Why: the compiler found a [ and reached the end without a matching ]. With backslashes inside a class, as in [^'\\], a layer can merge or consume backslashes so that \] escapes the bracket instead of closing the class. Splunk reads the pattern from a quoted search string, which is one more layer. We can't confirm Splunk's exact escaping rules, so treat Splunk's rex documentation as the authority and try these two experiments:
- Double each literal backslash again:
[^'\\]+\\[^\\]+becomes[^'\\\\]+\\\\[^\\\\]+inside the quotes. - Replace each literal backslash with the hex escape
\x5C:[^'\x5C]+\x5C[^\x5C]+. No backslash pairs are left to collapse.
Whichever you try, check the extracted field on several real events. A pattern that compiles can still match the wrong text.
Fix 3: C++ regex_match, PHP delimiters and match-all
Symptom: escaping looks right, still no match.
std::regex_matchneeds the whole string to match. Useregex_searchunless you mean a full match.- PHP patterns need delimiters. Write
'/\d+/', not'\d+'. Flags go after the closing delimiter:'/\d+/i'. If the pattern contains the delimiter, escape it or use another ('#...#'). - The global flag is not a code flag.
preg_matchreturns the first match andpreg_match_allreturns all. In PowerShell,-matchstops at the first match; use[regex]::Matches($text, $pattern)for all. - PowerShell
-matchignores case by default. Use-cmatchfor case-sensitive matching.
Fix 4: Your host uses a different regex engine
Symptom: correct escaping, still failing, often around lookbehind, named groups, or . and newlines.
Set regex101's flavor selector to the engine your code uses:
- PHP
preg_*uses PCRE, so choose PCRE2. - PowerShell
-matchand-replaceuse .NET, so choose .NET. - C++
std::regexdefaults to the ECMAScript grammar, so JavaScript is the closest flavor. It has no lookbehind and no named groups, so patterns using either fail however you escape them. - For Splunk
rex, read Splunk's regex documentation for anything unusual.
Also, . does not match a newline in most engines unless you enable a dot-matches-newline option, and that option must be set in code too.
Fix 5: You're not matching the text you tested
- PowerShell got different HTML than the browser.
Invoke-WebRequestreturns the raw response, while the browser inspector shows the page after JavaScript ran. Print$response.Contentand test against that. - Line endings. Files and servers may use
\r\nwhere your sample used\n, which breaks patterns with$or\n. - Invisible characters. A non-breaking space or zero-width character looks like a normal space when pasted.
Fix 6: Replacement strings and interpolation
- PowerShell:
"$1"in double quotes is read as a variable and comes out empty. Use'$1'. - PHP:
"\1"in double quotes is an octal escape. Use'$1','\1'or'${1}'. - PHP and PowerShell double quotes: any
$namein the pattern is interpolated. Prefer single quotes for patterns.
Checklist before you try again
- The raw pattern matches a sample of the real text.
- The string style is raw or single-quoted, or every backslash is doubled as the table shows.
- The printed string at run time equals what regex101 shows.
- Delimiters and flags are set in code.
- The engine flavor matches your host.
- You are matching the same text, line endings included.
Where Bytepliers helps, and where it doesn't
Bytepliers covers two parts: testing the raw pattern and producing a backslash-escaped version. It does not emulate PHP, C++, Splunk or PowerShell engines, and it does not generate a ready-made literal for a specific language.
- Regex Tester (⌘8) shows live matches, groups and the flags
i,m,sandx. It uses ICU syntax (Apple'sNSRegularExpression), which is not the engine PHP,std::regexor .NET use. Confirm the idea here, then confirm in your real runtime. regex101 is better for picking a flavor. - Escape / Unescape has a Style menu including Backslash (JSON / C / Swift) and Regex literal. Paste the working pattern, choose Escape and the style, and read the output before pasting it into code. The backslash style suits a C++ normal literal and a PHP double-quoted string, not PowerShell or PHP single quotes. To see what the engine receives, paste a literal's contents without quotes and choose Unescape.
- String Inspector shows line endings and highlights invisible characters, useful for Fix 5.
If regex101 and a terminal are enough, use those. Bytepliers is part of MacSuite and runs offline; see the Bytepliers page, the tool reference or the best regex testers for Mac.
If nothing works
Ask in the support channel for your runtime, such as Splunk's community and support, or the PHP or PowerShell documentation and forums. Include the engine and version, the exact code line with the literal as written, a printed sample of the real text, and the exact error text.
My regex works on regex101 (flavor: PCRE2) but not in my code.
Runtime/version: PHP 8.x
Code line: $pattern = '/^(\d+)\\(\w+)$/';
Printed pattern at run time: (paste output here)
Sample text (printed at run time): (paste here)
Error or result: (exact text)
Already tried: single quotes, 4 backslashes, preg_match_allCommon questions
Why do I need four backslashes in PHP single quotes?
PHP single quotes turn \\ into \. To give the regex engine \\ (a literal backslash), you must write four.
Is a raw string always the safest choice?
Usually, because the pattern stays as regex101 shows it. Check that your pattern doesn't contain the raw string's terminator, like )" in C++.
Which regex101 flavor should I pick for C++?
JavaScript is the closest to the default std::regex ECMAScript grammar, but it isn't identical. Test in your real runtime.
Does regex101's code generator remove the escaping problem?
It can save manual escaping, but verify its output by printing the string at run time.