2015-10-06 69 views
0

我有一个像字符串替换在Ruby on Rails的

details = "1. Command id = 22 Time = 2:30 <br> 2. Command id = 23 Time = 3:30" 

文本现在我需要把它转换成

"1. http://localhost:3000/command_id=22/home Time = 2:30 <br> 2. http://localhost:3000/command_id=23/home Time = 3:30" 

我用正则表达式和gsub但它不会做,因为gsub将取代同一字符串。然后有一些技术使用sedawk

提取所有ID,如22,23,我用

details.scan(/Command id = [0-9]+/).join(",").scan(/[0-9]+/) 

任何想法如何做到上面的转换?

+1

什么是你真正想达到什么目的?从字符串中删除'Command id ='还是提取id或两者? – Stefan

回答

1

只是一个空字符串

string.gsub(/\s*\bCommand\s+id\s+=/, "") 
+5

你可以提供一个字符串模式,即'gsub('Command id =','')' – Stefan

2

更换Command id =你为什么不只是使用

details.gsub(' Command id =', '') 

它产生预期的结果

"1. 22 Time = 2:30 <br> 2. 23 Time = 3:30" 

编辑:

details.gsub('Command id = ', 'http://localhost:8000/') 

它会生成

"1. http://localhost:8000/22 Time = 2:30 <br> 2. http://localhost:8000/23 Time = 3:30" 
+0

我编辑了我的文章。可以请你看看它。我想生成http链接。 –

+0

@TanishGupta编辑答案 –

0

试试这个纯粹的正则表达式,并得到您预期的输出

sed 's/[^"]\+\([^ ]\+\)[^=]\+=\([^\.]\+.\)[^=]\+.\(.*\)/\1\2\3/' FileName 

sed 's/Command id =\|details = //g' FileName 

输出:

"1. 22 Time = 2:30 <br> 2. 23 Time = 3:30" 
0
def parse_to_words(line)line.split ' ' 
end 

line = "1. Command id = 22 Time = 2:30 <br> 2. Command id = 23 Time = 3:30" 

words = parse_to_words line 

output= words[0] + 
     " http://localhost:3000/command_id=" + 
     words[4] + 
     "/home Time = " + 
     words[7] + 
     " <br> " + 
     words[9] + 
     " http://localhost:3000/command_id=" + 
     words[13] + 
     "/home Time = " + 
     words[16] 

输出:1. http://localhost:3000/command_id=22/home Time = 2:30 <br> 2. http://localhost:3000/command_id=23/home Time = 3:30

当然可以进一步自动化

+0

可以用sed来完成,如果是的话那怎么办? –

2

简单的regex

details.gsub(' Command id =', '') 

#=> "1. 22 Time = 2:30 <br> 2. 23 Time = 3:30" 
2
string.gsub('Command id =', '') 
相关问题