简体   繁体   中英

Ruby regex to remove newlines from specifc HTML tag?

Sorry I'm really bad at regexes, I finally hacked osmething to work in ruby. I'd appreciate if someone can instruct the proper way of how to do this:

I basically wanted to remove all \\n when it appears within ul tags.

while body =~ /<ul>.*(\n+).*<\/ul>/m
  body =~ /<ul>(.+)<\/ul>/m
  body.gsub!(
    /<ul>(.+)<\/ul>/m,
    "<ul>#{$1.gsub("\n","")}</ul>" )
end

The 2nd line took me forever to figure out, since the $1 was from the while loop, not actually from the gsub statement.

Thanks!

With regexp's TIMTOWTDI but here's one shorter attempt:

body.gsub!(/<ul>.*?<\/ul>/m) {|m| m.tr("\n",'') }

Basically find (non-greedily) all ul-tags and replace them with all linefeeds removed (check RDoc for String.gsub! and String.tr )

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