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.

1
  • Possible duplicates: here, and here. Commented Nov 30, 2014 at 21:59

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

This won't work if the department contains a non-word character such as a URL-encoded space, i.e. &department=Customer%20Service.
/department=(.+)&?/
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"

6 Comments

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=
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.
I don't think that \W does what you think it does. Maybe you had \b in mind.
@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.
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.