0

I am looking for a regex to extract URL params. My current solution is this:

(?i)key(?-i)=([^&]+)

but it fails on some of the tests below.

Lines where I want to match

cool=13&nice=zz&key=value&polo=0
Key=value&cool=13&nice=zz&polo=0
cool=13&nice=zz&polo=0&key=value

Lines I don't want to match it

cool=13&nice=zz&myKey=value&polo=0
3
  • 3
    Depending on which language you are using with this, it may already be available to you without regex. Commented Jun 19, 2018 at 19:16
  • 1
    If lookbehind is available then use: (?<=&|^)(?i)key(?-i)=[^&]* Commented Jun 19, 2018 at 19:23
  • oh, nice, I wasn't aware to lookbehind Commented Jun 19, 2018 at 19:24

1 Answer 1

1

URL parsing routines are available in many languages and it is recommended to use them as first choice.

However if you want to use regex for some reason, here is a lookbehind regex that you may use:

(?<=&|^)(?i)key(?-i)=[^&]*

Here (?<=&|^) is a lookbehind assertion that makes sure that there is a & or line start before matching key.

RegEx Demo

Sign up to request clarification or add additional context in comments.

2 Comments

(?-i) can be safely removed. [^&] will not be affected by the case insensitive modifier.
Yes, Agreed Wiktor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.