Skip to content

Dynamic filtering with regex #1062

@rigazilla

Description

@rigazilla

Is dynamic filtering supported for regex?

I mean something like $.tags[?(@ =~ $.regexPattern)].

Here's a reproducer:

///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS com.jayway.jsonpath:json-path:2.9.0

import com.jayway.jsonpath.JsonPath;
import java.util.List;

/**
 * JBang reproducer demonstrating that JsonPath does not support dynamic regex patterns.
 *
 * Problem: Cannot use a value from the JSON document as a regex pattern in filters.
 * For example: $.tags[?(@ =~ $.pattern)] does not work.
 *
 * Run with: jbang RegexDynamicPattern.java
 */
public class RegexDynamicPattern {

    public static void main(String[] args) {
        String json = """
        {
          "pattern": "/business/",
          "regexPattern": ".*compu.*",
          "tags": [
            "technology",
            "business",
            "cloud-computing",
            "data-science"
          ]
        }
        """;

        // static pattern - WORKS Result: ["business"]
            List<Object> result = JsonPath.read(json, "$.tags[?(@ =~ /business/)]");
            System.out.println("Result: " + result);

        // static regex pattern - WORKS Result: ["cloud-computing"]
            result = JsonPath.read(json, "$.tags[?(@ =~ /.*compu.*/)]");
            System.out.println("Result: " + result);

        // Attempt to use dynamic pattern from document - FAILS Result: []
            result = JsonPath.read(json, "$.tags[?(@ =~ $.pattern)]");
            System.out.println("Query: $.tags[?(@ =~ $.pattern)]");
            System.out.println("Result: " + result);

        // Attempt to use dynamic regEx from document - FAILS Result: []
            result = JsonPath.read(json, "$.tags[?(@ =~ $.regexPattern)]");
            System.out.println("Query: $.tags[?(@ =~ $.regexPattern)]");
            System.out.println("Result: " + result);
        System.out.println();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions