0

I want to get ASIA from following sample.

/scripts/skw.asp?term=&department=ASIA

Do you know how can I extract department value from whole text.

Johnny Cash
  • 4,867
  • 5
  • 21
  • 37
  • Possible duplicates: [here](https://stackoverflow.com/questions/7316656/how-to-get-query-string-from-passed-url-in-ruby-on-rails), and [here](https://stackoverflow.com/questions/2500462/how-to-extract-url-parameters-from-a-url-with-ruby-or-rails). – user4235730 Nov 30 '14 at 21:59

2 Answers2

1
string = "/scripts/skw.asp?term=&department=ASIA&a=b"    
puts string[/department=(\w+)/, 1] # => "ASIA"

or you can parse this as query(which is in my opinion more appropriate):

require 'cgi'

string = "/scripts/skw.asp?term=&department=ASIA&a=b" 
query        = string.split('?')[1] # => "term=&department=ASIA&a=b"
parsed_query = CGI::parse(query)    # => {"term"=>[""], "department"=>["ASIA"], "a"=>["b"]}
puts parsed_query['department'][0]  # => "ASIA"
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
0
str = '/scripts/skw.asp?term=&department=ASIA'

You could use a capture group:

str[/\bdepartment=(.+$)/, 1]
  #=> "ASIA"

or a positive lookbehind:

str[/(?<=\bdepartment=).+$/]
  #=> "ASIA"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • Though it is an interesting approach, both solutions will return incorrect result if there would be another parameter in the end or if you just switch positions of `term` and `department` in existing string like this `/scripts/skw.asp?department=ASIA&term=` – Rustam Gasanov Nov 30 '14 at 23:31
  • I assumed from the question that the string ends with the substring to be returned. If that's not the case, one would need to know how it would be determined where the substring to be returned ends. That is not given in the question and I've made no assumptions about where the string came from or how it will be used. – Cary Swoveland Dec 01 '14 at 00:17
  • I don't think that `\W` does what you think it does. Maybe you had `\b` in mind. – pguardiario Dec 01 '14 at 10:05
  • @pguardiario, sorry for the late reply. I don't want `\b` because "department" could be preceded by a non-alphameric character, as in the example. `\W ` is not quite that, but I thought it was close enough. – Cary Swoveland Dec 09 '14 at 23:13
  • It's the difference between checking for the existence of a non-word char and checking for the non-existence of a word char. `\b` is what you want there. – pguardiario Dec 10 '14 at 00:16
  • @pguardiario, you are correct, of course. (Did an edit.) What was I thinking? – Cary Swoveland Dec 10 '14 at 22:20