Extracting a value from query string using Regex

Viewed 92

I'm trying to extract the value from this string using regex but I can't seem to get it right.

string:

?Ntt=crockett%20&%20Jones&Rdm=718&searchType=simple&type=search&Ns=&N=&Nrpp=12&No=0&Nr=AND(product.active:1,NOT(record.type:Store))

I need the value of Ntt which is crockett%20&%20Jones.

The regex I have currently is:

\?Ntt=(([&%])|([^&=]))*

but this results in:

?Ntt=crockett%20&%20Jones&Rdm

How can I update my regex to produce the value I need?

2 Answers

You can use a capturing group based regex like

[&?]Ntt=((?:%20&%20|[^&])*)

See the regex demo.

Alternatively, you can use a lookbehind based regex like

(?<=[&?]Ntt=)(?:%20&%20|[^&])*

See the regex demo.

Details

  • (?<=[&?]Ntt=) - a positive lookbehind that matches a location that is immediately preceded with ? or & and then Ntt=
  • (?:%20&%20|[^&])* - a non-capturing group that matches zero or more occurrences of a %20&%20 substring or any char other than &.

[&\?]Ntt=([^&]*)

First capture the separator (either ? or &), then capture the key, then capture everything until the next separator.

Demo: https://regex101.com/r/VuXQXP/1

Related