简体   繁体   中英

How to search and replace string in ruby?

I tried the below code to search the string pattern "]]>*/-->" and replace it with "*/-->" using gsub function.

but instead of replacing whole string. it replaces character wise..

File.open('reporttestphp2.xml', 'r+') do |f1|     
  while line = f1.gets
    f1.puts line.gsub("]]>*/-->","*/-->")   
  end    
end

How can I replace the whole string pattern in Ruby?

The gsub works fine. You just need to read the file in a different way:

text = File.read("reporttestphp2.xml").gsub("]]>*/-->","*/-->")
File.open("out.xml", "w").write(text)

I hope, that helps.

为此,请使用ruby regex常量,

gsub(/]]>\*\/-->/, '*/-->')

What do you mean by whole string pattern? If you want to use regular expressions, they are written beetween / characers in ruby, eg /\\w+/

Examples

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