JSONPath Regex Filter — Pattern Matching in Filters
Apply regular expression pattern matching inside JSONPath filter expressions. Learn the =~ operator syntax for regex-based filtering of JSON data.
Detailed Explanation
Regex Filters in JSONPath
Some JSONPath implementations support regular expression matching inside filter expressions using the =~ operator. This lets you select elements whose string properties match a pattern, providing powerful text-based filtering.
Syntax
$.array[?(@.property =~ /pattern/flags)]
The regex is enclosed in forward slashes, with optional flags after the closing slash:
i— case-insensitiveg— global (rarely needed in filters)m— multiline
Example
Given:
{
"files": [
{ "name": "report-2024-01.pdf", "size": 1024 },
{ "name": "image-001.png", "size": 2048 },
{ "name": "report-2024-02.pdf", "size": 512 },
{ "name": "data-export.csv", "size": 4096 },
{ "name": "Report-Summary.PDF", "size": 768 }
]
}
$.files[?(@.name =~ /report.*\.pdf/i)]returns all three report files, including "Report-Summary.PDF" (case-insensitive).$.files[?(@.name =~ /^image/)]returns only "image-001.png".$.files[?(@.name =~ /\.(csv|pdf)$/i)]returns all CSV and PDF files.
Common Regex Patterns in JSONPath
| Pattern | Matches |
|---|---|
/^prefix/ |
Strings starting with "prefix" |
/suffix$/ |
Strings ending with "suffix" |
/\d{4}-\d{2}/ |
Date-like patterns (YYYY-MM) |
/^[A-Z]/ |
Strings starting with uppercase |
/error|warning/i |
"error" or "warning" (case-insensitive) |
Implementation Support
Regex filters are not part of the original JSONPath specification by Stefan Goessner. Support varies:
- Jayway JsonPath (Java): Full regex support with
=~ - jsonpath-plus (JavaScript): Supports regex via
=~ - Python jsonpath-ng: Limited regex support
- RFC 9535 (IETF JSONPath): Does not include regex as a standard operator
Always check your library's documentation before relying on regex filters in production.
Alternatives When Regex Is Not Available
If your JSONPath implementation does not support regex, you can:
- Extract all values with a wildcard and filter in application code.
- Use string comparison operators for prefix/suffix matching where possible.
- Pre-process the JSON data to add computed boolean fields.
Use Case
Use regex filters for pattern-based searching in JSON data — for example, finding all log entries matching an error pattern, filtering files by extension, selecting records where a field matches a specific naming convention, or searching through API responses for strings matching a format.