Search code examples
c#json.netjsonpath

JToken.SelectToken with regex for finding values that match a pattern?


How can I use JToken.SelectToken for finding values inside a path that match a pattern (e.g. find all values that are valid email addresses)? Is there any Regex compatibility like other frameworks support?


Solution

  • I'm not sure if this is documented anywhere (I didn't find at least), but actually in last versions (starting with 11.0.1 it seems) it does. Syntax is =~ /regex here/. For example:

    JObject o = JObject.Parse("{\"Objects\": [{\"Email\": \"[email protected]\"}, {\"Email\":\"not an email\"}]}");
    // returns only "[email protected]" token
    var result = o.SelectToken(@"$.Objects[?(@.Email =~ /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)]");