Is it possible to change only http
of URL ending with .png
to https
when there is a character string like the following?
str = 'kkk<a href="http://abcdege/hoge222/bar/t22est.md">aaab.png
bbb<a href="http://abcdege/ho22aage/bddfear/ted2st.png ">aaak
ubotabbbccxcb <a href="http://abcdege/22hoge/b22ar/tfeest.md">aa23a
bbkubotasbbb <a href="http://abcdege/hoffee11ge/bar/test.html">appkub
otapoooabbb<a href="http://abcdege/ho22aage/bddfear/ted2swwt.png ">ab
ddbbb.png'
I was quite worried. I tried to replace it using ruby's gsub (regular expression, string) method.
So, I wondered if there is a way to replace only a part of the match (URL) (http part this time).
I couldn't think of it with the above idea. In the first place, the idea of using only the gsub (regular expression, string) method may not have been good. There may be a way to use something like a regular expression block. ** However, in the end, I was able to create a procedure that would lead to the same result. ** **
Replace with 2-step sub.
".URL starting with png".gsub(http, "https")
It is a flow to replace with.
First, extract the URL from the string.
I wanted to use String # scan
here, but it seems that there is already a method called" Extract URL from string ". .. (too amazing)
Reference: Extract URL from string --Ruby Tips!
URI.extract(str)
#=> ["http://abcdege/hoge222/bar/t22est.md", "http://abcdege/ho22aage/bddfear/ted2st.png ", "http://abcdege/22hoge/b22ar/tfeest.md", "http://abcdege/hoffee11ge/bar/test.html", "http://abcdege/ho22aage/bddfear/ted2swwt.png "]
Then use these to determine and replace each one.
URI.extract(str).each do |uri|
if /.*(\.png)$/.match(uri)
new_uri = uri.sub("http","https")
str = str.sub(uri, new_uri)
end
end
str
#=> "kkk<a href=\"http://abcdege/hoge222/bar/t22est.md\">aaab.png \nbbb<a href=\"https://abcdege/ho22aage/bddfear/ted2st.png\">aaak\nubotabbbccxcb <a href=\"http://abcdege/22hoge/b22ar/tfeest.md\">aa23a\nbbkubotasbbb <a href=\"http://abcdege/hoffee11ge/bar/test.html\">appkub\notapoooabbb<a href=\"https://abcdege/ho22aage/bddfear/ted2swwt.png\">ab\nddbbb.png "
I feel that the point is to replace it with a two-step sub.
Recommended Posts