[英]Working with Named Regex Groups in Ruby
我試圖通過一系列的行來匹配正則表達式組,並感到困惑。 數據文件中的行如下所示:
2014-03-01 08:19,47.799107662994,-75.876391553881,some comment,James,#tag
這是我的Ruby代碼:
regex = /(?<day>.*)\s(?<hour>\d*:\d*),(?<lat>.*),(?<long>.*),(?<entry>.*),(?<people>.*),#(?<tag>.*)/
f = File.open("/Users/USERNAME/path/to/file.txt", encoding: 'UTF-8')
lines = f.read
f.close
lines.each_line do |line|
if line =~ /&/
line.gsub!(/[&]/, 'and')
end
if regex =~ line
puts line
end
end
那行得通, 但是如果我將倒數第三行更改為行,例如puts day
,那么我會收到一條錯誤消息,說那是未定義的局部變量。 我的理解是=~
自動定義了這些變量。
知道我在做什么錯嗎?
您只能通過matchdata
對象訪問已named regex
值
regex = /(?<day>.*)\s(?<hour>\d*:\d*),(?<lat>.*),(?<long>.*),(?<entry>.*),(?<people>.*),#(?<tag>.*)/
line = "2014-03-01 08:19,47.799107662994,-75.876391553881,some comment,James,#tag"
matchdata = regex.match(line)
matchdata["day"] # => "2014-03-01"
so I would do as below instead:
if (matchdata = regex.match(line))
puts matchdata["day"]
end
當命名的捕獲組與表達式左側的文字正則表達式和=〜運算符一起使用時,捕獲的文本也將分配給具有相應名稱的局部變量。
因此,它必須是用於創建局部變量的文字正則表達式。
在您的情況下,您正在使用變量來引用正則表達式,而不是文字。
例如:
regex = /(?<day>.*)/
regex =~ 'whatever'
puts day
NameError: undefined local variable or method `day' for main:Object
產生NameError: undefined local variable or method `day' for main:Object
,但這
/(?<day>.*)/ =~ 'whatever'
puts day
打印whatever
。
嘗試:
puts $~['day'] if regex =~ line
(有點神秘) $~
全局變量是一個MatchData實例,用於存儲最后一個正則表達式匹配的結果,您可以在其中訪問命名的捕獲。
但是@bjhaid的答案是一個更好的選擇,顯式保存MatchData。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.