2015-10-06 95 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 =', '') 
相關問題