1

I have this string:

rf=hello&ur=bello&au=yello

However position changes randomly with each new line, e.g.

au=yello&rf=hello&ur=bello

What regular expression would be needed now to fetch all rf=(a-z)+ where au == yello?

georg
  • 211,518
  • 52
  • 313
  • 390
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
  • 2
    No regex. Parse. Exactly how depends on your language. For PHP, try [`parse_str`](http://php.net/parse-str), as this will allow you to simply check `if( $arr['au'] == "yellow") echo $arr['rf'];` – Niet the Dark Absol Oct 23 '14 at 09:27
  • Aggree with above, you could use regex, but thats way more complex. You'd need lookbehinds, if available, or build crazy optional not-captured groups, etc. Could you tell us, which language you use? Maybe modify you question accordingly – martinczerwi Oct 23 '14 at 09:31
  • Python of course. So what is more T efficient? One RegEx with LookBehind/LookAheads or Two Regex with an if-clause in my code like Niet the Dark Absol suggested? – Stephan Kristyn Oct 23 '14 at 09:33
  • http://stackoverflow.com/questions/10113090/best-way-to-parse-a-url-query-string – georg Oct 23 '14 at 09:37
  • Unfortunately my real world input string is a bit more complicated - http://regexr.com/39pib – Stephan Kristyn Oct 23 '14 at 09:44

2 Answers2

1

Using regex you can use:

(?=.*?(?:^|&)au=yello(?:&|$)).*?(?:^|&)rf=([^&]+)

RegEx Demo

Parameter rf value is available in captured group #1.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Try this if group is not an option. (JS by example)

(rf=([a-z]+)(.+))*(au=yello)(.+)(rf=([a-z]+)(.+))*

it will check if rf=? is present before au=yello or if rf=? is present after.

Feel free to simplify parenthesis.