0

I'm having trouble with a regex in Ruby (on Rails). I'm relatively new to this.

The test string is: http://www.xyz.com/017010830343?$ProdLarge$

I am trying to remove "$ProdLarge$". In other words, the $ signs and anything between.

My regular expression is: \$\w+\$

Rubular says my expression is ok. http://rubular.com/r/NDDQxKVraK

But when I run my code, the app says it isn't finding a match. Code below:

some_array.each do |x|
   logger.debug "scan #{x.scan('\$\w+\$')}"
   logger.debug "String? #{x.instance_of?(String)}"

   x.gsub!('\$\w+\$','scl=1')

   ...

My logger debug line shows a result of "[]". String is confirmed as being true. And the gsub line has no effect.

What do I need to correct?

1
  • You're passing a string containing a regex instead of an actual regex. Commented Jan 14, 2013 at 20:13

2 Answers 2

5

Use /regex/ instead of 'regex':

> "http://www.xyz.com/017010830343?$ProdLarge$".gsub(/\$\w+\$/, 'scl=1')
=> "http://www.xyz.com/017010830343?scl=1"
Sign up to request clarification or add additional context in comments.

Comments

2

Don't use a regex for this task, use a tool designed for it, URI. To remove the query:

require 'uri'

url = URI.parse('http://www.xyz.com/017010830343?$ProdLarge$')
url.query = nil

puts url.to_s
=> http://www.xyz.com/017010830343

To change to a different query use this instead of url.query = nil:

url.query = 'scl=1'

puts url.to_s
=> http://www.xyz.com/017010830343?scl=1

URI will automatically encode values if necessary, saving you the trouble. If you need even more URL management power, look at Addressable::URI.

2 Comments

thanks. I didn't realize URI was so handy. In this particular app, I believe need to use some form of regex because the queries can actually get a lot more complex than the example here. But I'll apply this somewhere.
We can't help you unless you show accurate examples of what you're up against. Add your other examples to your original question by editing it.

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.