0

I am trying to use regex to match a query string pattern and am having some issues. The URL is "http:www.domain.com/dir/page.aspx". This page can have a variety of query string vaiables and values attached in a non-specific order. What i want to do is get the value of one of these variables and use it. Thus, for all of these examples:

http:\\www.domain.com/dir/page.aspx?city=name
http:\\www.domain.com/dir/page.aspx?area=codes&city=name
http:\\www.domain.com/dir/page.aspx?area=codes&city=name&state=ofmind
http:\\www.domain.com/dir/page.aspx?city=name&state=ofmind
http:\\www.domain.com/dir/page.aspx?area=codes&state=ofmind&city=name
http:\\www.domain.com/dir/page.aspx?area=codes&city=name&state=ofmind&dat=dis&foo=bar

I want to extract the value "name" from the city variable and use it. What I've come up thus far is:

/dir\/page.aspx\?(.*&)?city=(.*)(?=&.*)/

and using $2 for that value.

This works ok for some cases but doesnt seem to catch them all. I believe my issue is here:

city=(.*)

and that I need to stop capturing at the first appearance of an ampersand, but my random copy and paste efforts have not been successful. Can anyone explain how I would catch any and all characters until a particular one appears?

user1026361
  • 3,627
  • 3
  • 22
  • 20
  • 1
    possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Benjamin Gruenbaum Mar 27 '14 at 21:40
  • 1
    Note, the difference between this and the duplicate is that here you're not using `.location` - so swap that out when you use that code. – Benjamin Gruenbaum Mar 27 '14 at 21:40
  • Quit edit here. I'm working primarily in javascript but I mislabeld this question. I'm actually looking to do this within a Tomcat redirect rule – user1026361 Mar 27 '14 at 21:41
  • 1
    are you trying to do the matching in javascript regex? – attila Mar 27 '14 at 21:41
  • I'm testing my patterns using javascript but this will be deployed as a redirect rule on Tomcat – user1026361 Mar 27 '14 at 21:43

1 Answers1

2

This will be on capture $2

/dir\/page.aspx\?(.*&)?city=([^&]*)/

This will be on capture $1

/dir\/page.aspx\?(?:.*&)?city=([^&]*)/
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85