2

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
Tommy
  • 965
  • 6
  • 13
  • 21

3 Answers3

2
string = "test\r\nfoo\r\ntest\r\nbar"
string = string.gsub(/^test(?=\r?\n)/, 'X\&X').delete(?\r)
puts string
user21033168
  • 444
  • 1
  • 4
  • 13
0

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.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • My program definitely does not have a typo. If I print my inputted string I get "test\r\nfoo\r\nbar\r\ntest" Does it not match the \r's or something? – Tommy Apr 13 '13 at 20:26
  • puts "test\r\nfoo\r\nbar\r\ntest".gsub(/^(.*)$/, 'X\1X') that outputs what I've showed with the Xtest Xfoo Xbar XtestX – Tommy Apr 13 '13 at 20:29
0

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.

A human being
  • 1,220
  • 8
  • 18