[英]Ruby: Gsub - multiple string replacements in a single line [in an array]
is there a way to replace multiple strings in a single line of array using gsub. 有没有一种方法可以使用gsub替换数组的一行中的多个字符串。
here is the log file 这是日志文件
13:29:00 (alex) OUT: "72500_2010_0F" abcd@S400532
13:31:12 (alex) IN: "72600_2010_0F" abnc@S403818
13:31:52 (alex) IN: "71200_2010_0F" osa@S400583
I would like to replace the below 我想替换以下
(alex) with ""
OUT: with OUT
IN: with IN
"72500_2010_0F" with XYZ
"71200_2010_0F" with QWE
"72600_2010_0F" with UIO
The original file (log file) is put into array and I wanted to read each line in the array and perform gsub. 原始文件(日志文件)放入数组中,我想读取数组中的每一行并执行gsub。 Dont want to use Hash as its lil complicated -As being Ruby Beginner...& to Regex...
不想使用Hash作为其复杂的工具-由于是Ruby Beginner ...&正则表达式...
array1.each do |element|
i = element.gsub(/?????????/) [ What should go here]
array2.push(i)
end
I dint want to make changes to original array but push the modified lines into different array ie array2 我不希望对原始数组进行更改,但将修改后的行推入不同的数组,即array2
What is the best & easy to understand code to do this? 什么是最好的和易于理解的代码来做到这一点? - Please help
- 请帮忙
Looking at String#sub it seems there are many ways to do what you want: 看一下String#sub ,看来有很多方法可以完成您想要的事情:
One approach can be to use a hash as second parameter 一种方法是使用哈希作为第二个参数
def cleansed_log_line(line) replacement_rules = { 'alex' => '', 'OUT: ' => 'OUT ', 'IN: ' => 'IN ' } matcher = /#{replacement_rules.keys.join('|')}/ line.gsub(matcher, replacement_rules) end
Another approach can be to to use block form 另一种方法可以是使用块形式
def cleansed_log_line(line) replacement_rules = { 'alex' => '', 'OUT: ' => 'OUT ', 'IN: ' => 'IN ' } matcher = /#{replacement_rules.keys.join('|')}/ line.gsub(matcher) do |match| replacement_rules[match] || match end end
Another not so good implementation 另一个不太好的实现
def cleansed_log_line(line) replacement_rules = { /alex/ => '', 'OUT: ' => 'OUT ', 'IN: ' => 'IN ' } replacement_rules.each do |match, replacement| line = line.gsub(match, replacement) end line end
Hashes and RegEx are nothing to worry about. 哈希和RegEx无需担心。 This function can cleanse any line passed to it and would return a cleansed line.
此函数可以清除传递给它的任何行,并返回已清除的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.