Question

I'm writing ruby and need some help with regex. And I'm really noob in regexp. I have a string like this

/hello/world

I would like to #gsub this string to change the second slash to %2F. The challange for me to ignore the first slash and to change only the second slash. I tried this one

[^/]/

but it chooses not clean slash but o/ in

/hello/world

Please, help me. Thanks!!

Was it helpful?

Solution

You can simply capture the character before the slash in a group and use that in the replacement, for example:

"/hello/world".gsub(/([^\/])\//, '\1%2F') #=> "/hello%2Fworld"

Or if you just want to match any / that appears after the first character, you can simplify this to:

"/hello/world".gsub(/(.)\//, '\1%2F')     #=> "/hello%2Fworld"

Or like this:

"/hello/world".gsub(/(?<!^)\//, '%2F')    #=> "/hello%2Fworld"

OTHER TIPS

And now for an uglier, regexless alternative:

"/hello/world".split("/").tap(&:shift).unshift("/").join("")

I'll see myself out.

You need to use subpattern within () for find substring:

/^\/(.*)$/

or

/^.(.*)$/

this pattern excluding first character. And then replace / in this substring

(?!^\/)\/

http://rubular.com/r/IRWptAJdLs is a a working example.

change the second / to %2F:

'/hello/world'.sub /(\/.*?)\//, '\1%2F'
#=> "/hello%2Fworld"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top