Ruby正则表达式匹配输入的文本文件字符串中的一行 [英] Ruby regex matching a line in an inputted text file string
问题描述
我需要匹配输入的文本文件字符串中的一行,并用例如字符将捕获的行换行.
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
我想用gsub输出:
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.
我尝试过
string = string.gsub(/^(.*)$/, 'X\1X')
这将输出:
Xtest
Xfoo
Xtest
Xbar
...为什么?
好的,所以我在文本文件的最后一行退格了,现在我得到了...
Okay so I backspaced the last line of the text file and now I am getting this...
Xtest
Xfoo
Xbar
XtestX
推荐答案
string = "test\r\nfoo\r\ntest\r\nbar"
string = string.gsub(/^test(?=\r?\n)/, 'X\&X').delete(?\r)
puts string
这篇关于Ruby正则表达式匹配输入的文本文件字符串中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!