JamesNK/Newtonsoft.Json · error · JsonException
Path ended with an open regex.
Error message
Path ended with an open regex.
What it means
Thrown by ReadRegexString when a JSONPath regex literal (/pattern/flags) is opened with '/' but the closing '/' is never found before end-of-input. The regex was started (e.g. via =~ operator) but never terminated.
Source
Thrown at Src/Newtonsoft.Json/Linq/JsonPath/JPath.cs:750
if (char.IsLetter(currentChar))
{
_currentIndex++;
}
else
{
break;
}
}
return _expression.Substring(startIndex, _currentIndex - startIndex);
}
else
{
_currentIndex++;
}
}
throw new JsonException("Path ended with an open regex.");
}
private bool Match(string s)
{
int currentPosition = _currentIndex;
for (int i = 0; i < s.Length; i++)
{
if (currentPosition < _expression.Length && _expression[currentPosition] == s[i])
{
currentPosition++;
}
else
{
return false;
}
}
_currentIndex = currentPosition;View on GitHub (pinned to 4f73e74372)
Solutions
- Terminate the regex with a second '/' and optional trailing flags (letters).
- Escape literal '/' inside the pattern as \\/ so it is not treated as the terminator.
- Test the regex query against a known token in a unit test.
Example fix
// before
token.SelectTokens("$..[?(@.name =~ /bob");
// after
token.SelectTokens("$..[?(@.name =~ /bob/i]"); Defensive patterns
Strategy: validation
Validate before calling
static bool RegexClosed(string path)
{
bool inRegex = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == '/' && (i == 0 || path[i-1] != '\\')) inRegex = !inRegex;
}
return !inRegex;
} Try / catch
try { token.SelectTokens(path).ToList(); }
catch (JsonException ex) when (ex.Message == "Path ended with an open regex.")
{ /* regex literal missing closing slash */ } Prevention
- Always terminate regex literals with a second '/'.
- Escape literal '/' as \\/ inside the pattern.
When it happens
Trigger: A query using the =~ regex operator whose pattern is never closed. Example: token.SelectTokens("$..[?(@.name =~ /bob") — the regex opens but no second '/' appears, so the parser runs to the end of the string.
Common situations: Writing a regex query and forgetting the closing slash; constructing regex from user input that itself contains slashes consumed as part of the pattern; assuming flags must come before the closing slash.
Related errors
- Path ended with open query.
- Unknown escape character: \
- Path ended with an open string.
- Could not read query operator.
- Index {0} outside the bounds of JArray.
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/dc52b15856698cc6.
Report an issue: GitHub.