Ruby regex gsub a line in a text file

前端 未结 5 602
旧巷少年郎
旧巷少年郎 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:02

    string.gsub(/^(matchline)$/, 'X\1X') Uses a backreference (\1) to get the first capture group of the regex, and surround it with X

    Example:

    string = "test\nfoo\ntest\nbar"
    string.gsub!(/^test$/, 'X\&X')
    p string
    => "XtestX\nfoo\nXtestX\nbar"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 21:08

    If your file is input.txt, I'd do as following

    File.open("input.txt") do |file|
      file.lines.each do |line|
        puts line.gsub(/^(.*)$/, 'X\1X')
      end
    end
    
    • (.*) allows to capture any characters and makes it a variable Regexp
    • \1 in the string replacement is that captured group

    If you prefer to do it in one line on the whole content, you can do it as following

     File.read("input.txt").gsub(/^(.*)$/, 'X\1X')
    
    0 讨论(0)
  • 2020-12-19 21:16

    You can do it in one line like this:

    IO.write(filepath, File.open(filepath) {|f| f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)})
    

    IO.write truncates the given file by default, so if you read the text first, perform the regex String.gsub and return the resulting string using File.open in block mode, it will replace the file's content in one fell swoop.

    I like the way this reads, but it can be written in multiple lines too of course:

    IO.write(filepath, File.open(filepath) do |f|
        f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)
      end
    )
    
    0 讨论(0)
  • 2020-12-19 21:26

    Chomp Line Endings

    Your lines probably have newline characters. You need to handle this one way or another. For example, this works fine for me:

    $ ruby -ne 'puts "X#{$_.chomp}X"' /tmp/corpus
    XtestX
    XfooX
    XtestX
    XbarX
    
    0 讨论(0)
提交回复
热议问题