Ruby regex gsub a line in a text file

前端 未结 5 611
旧巷少年郎
旧巷少年郎 2020-12-19 20:42

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:

<         


        
5条回答
  •  半阙折子戏
    2020-12-19 21:06

    If you're trying to match every line, then

    gsub(/^.*$/, 'X\&X')
    

    does the trick. If you only want to match certain lines, then replace .* with whatever you need.

    Update:

    Replacing your gsub with mine:

    string = IO.read(ARGV[0])
    string = string.gsub(/^.*$/, 'X\&X')
    puts string
    

    I get:

    $ gsub.rb testfile
    XtestX
    XfooX
    XtestX
    XbarX
    

    Update 2:

    As per @CodeGnome, you might try adding chomp:

    IO.readlines(ARGV[0]).each do |line|
      puts "X#{line.chomp}X"
    end
    

    This works equally well for me. My understanding of ^ and $ in regular expressions was that chomping wouldn't be necessary, but maybe I'm wrong.

提交回复
热议问题