Reputation: 1157
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!!
Upvotes: 3
Views: 8972
Reputation: 54984
change the second /
to %2F
:
'/hello/world'.sub /(\/.*?)\//, '\1%2F'
#=> "/hello%2Fworld"
Upvotes: 0
Reputation: 149010
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"
Upvotes: 3
Reputation: 13521
And now for an uglier, regexless alternative:
"/hello/world".split("/").tap(&:shift).unshift("/").join("")
I'll see myself out.
Upvotes: 2
Reputation: 575
(?!^\/)\/
http://rubular.com/r/IRWptAJdLs is a a working example.
Upvotes: 1
Reputation: 12306
You need to use subpattern within ()
for find substring:
/^\/(.*)$/
or
/^.(.*)$/
this pattern excluding first character. And then replace /
in this substring
Upvotes: 1