3

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99

1 Answers1

4

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\": \"test@gmail.com\"}, {\"Email\":\"not an email\"}]}");
// returns only "test@gmail.com" token
var result = o.SelectToken(@"$.Objects[?(@.Email =~ /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)]");
Evk
  • 98,527
  • 8
  • 141
  • 191
  • I actually tried that before and recieved an `exception:Newtonsoft.Json.JsonException: 'Could not read query operator.'`. Which json.net version are you using? – Amir Popovich Mar 13 '18 at 12:45
  • @AmirPopovich I'm using last nuget version, which is 11.0.1 – Evk Mar 13 '18 at 12:46
  • Upgraded from 10.3 to 11 and this did work. Probably a new feature. Thank you for your answer. – Amir Popovich Mar 13 '18 at 12:47
  • Regarding documentation, support for regular expressions is mentioned in the [11.0.1 release notes](https://github.com/JamesNK/Newtonsoft.Json/releases/tag/11.0.1): *New feature - Added support for regex operator in JSON Paths*. And it's described in a [blog post](http://james.newtonking.com/archive/2018/02/22/json-net-11-0-release-1-net-standard-2-0-jsonconverters-json-path-and-more) by James Newton-King: *Json.NET 11 adds support for the regular expression operator in JSON Path queries... *. The blog post shows use of the `=~` operator for regex matching. – dbc Apr 23 '18 at 21:42