2014-06-17 23 views
-1

我想分析下面的文本,並查找與'+''-'啓動線:如何解析由行文本和一些值存儲在數組中

--- a/product.json 
+++ b/product.json 
@@ -1,4 +1,4 @@ 
{ 
- "name": "Coca Cola", 
- "barcode": "41324134132" 
+ "name": "Sprite", 
+ "barcode": "41324134131" 
} 
\ No newline at end of file 

當我找到一個這樣的行,我想存儲屬性名稱。即,用於:

- "name": "Coca Cola", 

我想存儲nameminus_array

+0

看起來你正在解析'diff'結果。你可以試試[unified_diff gem](https:// github。COM/rkneufeld/unified_diff)。免責聲明:我從來沒有使用那個寶石。 – zwippie

+0

像'--- a/product.json'這樣的行的屬性名稱是什麼? – sawa

+0

當您詢問代碼時,您需要顯示您嘗試的內容並解釋爲什麼它不適合您。有關如何正確提問的更多信息,請參見[help/on-topic],特別是#3。 –

回答

2

你要遍歷線,並查找與任-+開始跟空格線:

text = %[ 
--- a/product.json 
+++ b/product.json 
@@ -1,4 +1,4 @@ 
{ 
- "name": "Coca Cola", 
- "barcode": "41324134132" 
+ "name": "Sprite", 
+ "barcode": "41324134131" 
} 
\ No newline at end of file 
] 

text.lines.select{ |l| l.lstrip[/^[+-]\s/] }.map{ |s| s.split[1] } 
# => ["\"name\":", "\"barcode\":", "\"name\":", "\"barcode\":"] 
  • lines在行尾分割一個字符串,返回整行,包括尾隨行尾字符。
  • lstrip刪除行首的空白。這是規範化線,使正則表達式模式更簡單。
  • l.lstrip[/^[+-]\s/]是一點點Ruby String,基本上說是將模式應用到字符串並返回匹配的文本。如果沒有匹配的字符串nil將被返回,就select而言,它將作爲虛假來使用。如果字符串的內容與模式匹配,則[]將返回文本,該文本充當select的真實值,然後傳遞該字符串。
  • map遍歷select傳遞給它的所有元素,並通過將元素拆分爲空格來轉換該元素,這是split的默認行爲。 [1]在字符串中返回第二個元素。

下面是同一個地方的備用路徑:

ary = [] 
text.lines.each do |l| 
    i = l.strip 
    ary << i if i[/^\{$/] .. i[/^}$/] 
end 
ary[1..-2].map{ |s| s.split[1] } # => ["\"name\":", "\"barcode\":", "\"name\":", "\"barcode\":"] 

這將讓你開始。如何刪除重複項,去掉前導/尾隨雙引號和冒號是你的任務。

+0

這工作。我使用這個來創建兩個數組。一個具有前面的屬性,另一個具有「+」。所以,不會有重複。因此,我現在找不到交點,聯合和差異來標記文件中添加,刪除和更改的行。日Thnx – enter08

0
text.split(/\n/).select { |l| l =~ /^\+./ } 

如果您正在使用的文件:

File.open('your_file.txt', "r").select { |l| l =~ /^\+./ } 
+1

這是我的問題的一部分。這是輸出:'[「+++ b/product.json」,「@@ -1,4 +1,4 @@」,「+ \」name \「:\」Sinalco \「,」,「 + \「條碼\」:\「41324134131 \」「]'第一行是預期的。我會以某種方式跳過它。輸出中的第二行不正確。修正了:'.select {| l | l =〜/^\+./}「我想我會處理剩下的事情。 Thnx – enter08

+0

糟糕。你是對的。將編輯。 – Headshota

+0

@ enter08如果你認爲在'+'後面有一個空格,你可以使用:'text.split(/ \ n /)。select {| l | l =〜/^\+\s./}' –

0
File.readlines("file.txt").each do |line| 
    if line.starts_with? '+ ' || line.starts_with? '- ' 
     words = line.split(":") 
     key = words[0].match(/".*"/) 
     val = words[1].match(/".*"/) 
     # You can then do what you will with the name and value here 
     # For example, minus_array << if line.starts_with? '-' 
    end 
end 

我不完全相信你有這個限制的,所以我不能給出一個更具體的答案。基本上,你可以用File.readlines('file') { }迭代文件的行。然後我們檢查以+-開頭的字符串,並相應地獲取名稱和值。我在starts_with?中放了一個空格,因爲如果我沒有,它也會匹配您示例的前兩行。

希望這就是你要找的!

+0

看起來非常好。只是,如何使這個工作的字符串(文本)。我試過'@diffs [0] .diff.lines.each do | line | ...結束「# – enter08

0

根據第一個字符使用group_by到組:

groups = text.lines.group_by { |l| l[0] } 

groups['-'] 
# => ["--- a/product.json\n", "- \"name\": \"Coca Cola\",\n", "- \"barcode\": \"41324134132\"\n"] 
groups['+'] 
# => ["+++ b/product.json\n", "+ \"name\": \"Sprite\",\n", "+ \"barcode\": \"41324134131\"\n"] 
相關問題