In a file there are many of the following:
<p style= "Display:none" > This topic selected D.
....
....
....
</p>
And I want to achieve the function is to replace it:
<div style= "Display:none" class= "Sl_explain" > This topic selected D.
.....
.....
.....
</div>
This thing looks a little bit simple, but I spent half a day to realize this function, mainly for a long time did not write Ruby program, so the API is unfamiliar; second, I am not familiar with regular expressions, especially Ruby's regular expressions, and finally, because some details are not considered enough.
To achieve these functions, you can be divided into two steps, the first step is to
<p style= "Display:none" > This topic selected D.
....
....
....
</p>
is replaced with the following:
<p style= "Display:none" > This topic selected D. ............</p>
This form, why replace it, because in the read file is, need a line to read, so there is \ n, this line can not read, then in the regular expression match, naturally will not match. To implement replacements and replace them only
<p style= "Display:none" > This topic selected D. ............</p>
Internal \ n, need some restrictions, the specific implementation code is as follows:
File.Open ("Logic fill in the blanks 2.htm", "w") do |test|
File.Open ("Logic fill in the blanks. htm", ' r:gbk ') do |file|
File.each_line do | line|
if (line.start_with?) (' <p style= "Display:none" > ") &&!line.end_with? ("</p>\n"))
line.gsub! (Regexp.new (' \ n '), ')
End Test.print Line end end
The content that is about to be replaced is placed in a new file, "Logical Fill 2.html" (note 1, the above output to the file, the use of print, rather than puts, otherwise it will naturally add a \ n, then White replaced; note 2, the top of the end_with, plus a \ n, Since the end of this line is read, there is also an invisible newline character \ n, note 3, sometimes <p style= "Display:none" > there will be spaces before, so you can change Start_with to include, and then read this file, The replacement is then replaced with the regular expression, and the replaced content is placed in "test.html":
File.Open ("test.html", "w") do |test|
File.Open ("Logic fill in the blanks 2.htm", ' R ') do |file|
File.each_line do | line|
line.gsub! (Regexp.new (' <p style= "Display:none" > (. *) </p> '), ' <div style= ' display:none ' class= ' ' Sl_explain ' >\ 1</div> ') test.puts line end end
In this way, I want to achieve the function is achieved, in addition, if the file is not a row to read, it can be done in a multiline matching way:
Regexp.new (' <p style= "Display:none" > (. *) </p> ', regexp::multiline)
Unfortunately, I only came up with a line-by-row reading method, so multiline matching mode is useless.