【问题标题】:Ruby remove comma after a stringRuby 删除字符串后的逗号
【发布时间】:2017-05-13 16:03:53
【问题描述】:

我有多个以下格式的文件

例如。文件:sample.txt

id = class\234ha, class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87, class\234ha
cko = cyr\hui87

我正在查找字符串并将其从多个文件中删除。例如,查找并删除字符串 - class\234ha。

我的代码工作正常,它删除了所有预期的字符串,但在删除预期或标记的字符串后,行尾有一个尾随逗号。

例如。删除字符串后的 sample.txt - class\234ha

id = class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87,
cko = cyr\hui87

我想删除 ret\oiu87, 之后的最后一个逗号only。对于多个文件,它应该是相同的。我不确定逗号后是否有换行符或空格。我怎样才能让它工作。提前致谢。

代码

 pool = ''
svn_files = Dir.glob("E:\work'*-access.txt")

value=File.open('E:\nando\list.txt').read
value.each_line do |line|
    line.chomp!
    print "VALUE: #{line}\n"
    svn_files.each do |file_name|
      text = File.read(file_name)
      replace = text.gsub( /#{Regexp.escape(line)}\,\s/, '').gsub( /#{Regexp.escape(line)}/, '' )

      unless text == replace

        text.each_line do |li|
          if li.match(/#{Regexp.escape(line)}/) then
           #puts "Its matching"
           pool = li.split(" ")[0] 
          end
        end 
        File.open('E:\Removed_users.txt', 'a') { |log| 
        log.puts "Removed from: #{file_name}"
        log.puts "Removed user : #{line}"
        log.puts "Removed from row :#{pool}"
        log.puts "*" * 50 
        }
        File.open(file_name, "w") { |file| file.puts replace }
      end
    end
end

【问题讨论】:

    标签: ruby


    【解决方案1】:

    复杂的正则表达式是邪恶的。除非您的应用程序域确实需要它们,否则不要使用它们。相反,做多次传球。我不太确定您的预期替换是什么,但在结构上这是您想要做的:

    # Create an interim string using your existing substitutions. For example,
    # the corpus you currently have after substitutions contains:
    tmp_str = <<~'EOF'
      id = class\poi23, class\opiuj, cap\7y6t5
      dept = sub\6985de, ret\oiu87, 
      cko = cyr\hui87EOF
    EOF
    
    # Remove trailing commas.
    final_str = tmp_str.gsub /,\s*$/m, ''
    
    puts final_str
    

    这会将以下输出发送到屏幕:

    id = class\poi23, class\opiuj, cap\7y6t5
    dept = sub\6985de, ret\oiu87
    cko = cyr\hui87EOF
    

    使用这种方法,无论您是逐行还是在多行字符串上工作都没有关系。无论哪种方式,您都只是在每行末尾删除逗号和尾随空格。简单!

    【讨论】:

    • 我已经按照您的建议尝试过,但没有成功。我现在已经在问题中提出了我的整个代码。非常感谢您查看我的查询。
    • 我已经修改了代码,您建议在正则表达式中包含 * 是关键。非常感谢。对不起,我没有足够的声誉,所以我不能投票
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多