-1

Here is my string:

string = "abcdef.sfdsf_3asafds-fdsfd;info=<http://www.amazon.com:8080/abc/ads/asdf>;tag=abc123;val=hello"

My goal using gsub/sub in ruby to replace:

info=<http://www.amazon.com:8080/abc/ads/asdf>

with:

info=<private-url>

I tried a few attempts using regexp but they are buggy. Any advice?

Gaurav
  • 29
  • 5

1 Answers1

1

A simple regex to do it can be /<(.*?)>/

This will match everything inside < > (including the < > signals).

Keep in mind that this will match the first occurrence on string.

You can check the explanation for the regex on this question.

You can also check it on Rubular, a great tool to test ruby regex on fly.

In order to replace the match result in Ruby you can try something like 2.4.0 :024 > string.sub(/<(.*?)>/, '<your_url>') => "abcdef.sfdsf_3asafds-fdsfd;info=<your_url>;tag=abc123;val=hello"

This can be used on this string, but you need to adapt it on your use if there are more < > signals on the string.

Iuji Ujisato
  • 98
  • 1
  • 8
  • 1
    It's worth noting here that `<.*>` means *longest* possible match, while `<.*?>` means *shortest* possible. The difference here is how you avoid your expression getting too "greedy". – tadman Jul 22 '17 at 23:09
  • Sorry, I didn't worte that becaus I've linked another question that explains it. Should I copy/paste it here for better understanding for future viewers? – Iuji Ujisato Jul 26 '17 at 20:02