问题
I need to match a line in an inputted text file string and wrap that captured line with a character for example.
For example imagine a text file as such:
test
foo
test
bar
I would like to use gsub to output:
XtestX
XfooX
XtestX
XbarX
I'm having trouble matching a line though. I've tried using regex starting with ^ and ending with $, but it doesn't seem to work? Any ideas?
I have a text file that has the following in it:
test
foo
test
bag
The text file is being read in as a command line argument.
So I got (for example just trying to wrap test)
string = IO.read(ARGV[0])
string = string.gsub(/^(test)$/,'X\1X')
puts string
It outputs the exact same thing that is in the text file.
I've tried
string = string.gsub(/^(.*)$/, 'X\1X')
This outputs:
Xtest
Xfoo
Xtest
Xbar
...why?
Okay so I backspaced the last line of the text file and now I am getting this...
Xtest
Xfoo
Xbar
XtestX
回答1:
string = "test\r\nfoo\r\ntest\r\nbar"
string = string.gsub(/^test(?=\r?\n)/, 'X\&X').delete(?\r)
puts string
回答2:
It works fine for me in Ruboto IRB on my phone. Could you make a self-contained one-line example and post it? No file IO should be necessary. What ruby version do you use?
I suspect your program just has a typo.
回答3:
Problem is because of dos line endings(\r\n), so for getting rid of this, there is a flip
command (in MAC, if I'm correct) for converting dos line endings to mac line endings(\r). Search for it and convert dos line endings to mac line endings before using that text file.
来源:https://stackoverflow.com/questions/15992136/ruby-regex-matching-a-line-in-an-inputted-text-file-string