简体   繁体   中英

Ruby on Rails string scan and regular expression

I wanted to get image url "http://www.test.com/image.jpg" out from the string:

"<img align="right" alt="Title " src="http://www.test.com/image.jpg" width="120" /><"

Here is the code that i have:

module MyHelper

    def getMymage(allDesc)
        allDesc = "<img align="right" alt="Title " src="http://www.test.com/image.jpg" width="120" /><"
        allDesc = allDesc.scan(src="(\S+)")
    end
end

I got the following error: syntax error, unexpected tAMPER allDesc = allDesc.scan(src="(\\S+)")

syntax error, unexpected $undefined allDesc = allDesc.scan(src="(\\S+)")

How to fix it?

Thanks in advanced.

无法评论sunkencity的答案,但是解决破折号问题的正则表达式是:

/src=\"([a-z0-9_.\-:\/]+)"/i

The regexp is missing a start "/" and some extra stuff

allDesc.scan(/src=\"([a-z0-9_.\-:\/]+)"/i)

but you get an array as a response:

=> [["http://www.test.com/image.jpg"]] 

I'd suggest using the matching operator and then use the first match variable:

allDesc =~ /(http:\/\/[a-z0-9_.-i\/]+)/ && $1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM