Working with Named Regex Groups in Ruby

craigeley

I'm trying to match regex groups over a series of lines and getting stumped. Data file has lines that look like this:

2014-03-01 08:19,47.799107662994,-75.876391553881,some comment,James,#tag

Here is my Ruby code:

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

That works, but if I change that third to last to line to, for example puts day, then I get an error saying that is an undefined local variable. My understanding was that =~ automatically defined those variables.

Any idea what I'm doing wrong?

matt

From the Ruby Rexexp docs:

When named capture groups are used with a literal regexp on the left-hand side of an expression and the =~ operator, the captured text is also assigned to local variables with corresponding names.

So it needs to be a literal regex that is used in order to create the local variables.

In your case you are using a variable to reference the regex, not a literal.

For example:

regex = /(?<day>.*)/
regex =~ 'whatever'
puts day

produces NameError: undefined local variable or method `day' for main:Object, but this

/(?<day>.*)/ =~ 'whatever'
puts day

prints whatever.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Capturing named groups in regex with re.findall

来自分类Dev

Ruby regex: operator and

来自分类Dev

Ruby Regex组替换

来自分类Dev

Ruby Regex“包含”

来自分类Dev

Ruby Regex多次匹配

来自分类Dev

Finding in regex pattern the name of possible groups

来自分类Dev

PowerShell script string interpolation with named parameters is not working

来自分类Dev

Grails 2.4 named configuration for JSON not working

来自分类Dev

使用Regex的CRUD文本-Ruby

来自分类Dev

Ruby Regex:解析C ++类

来自分类Dev

Ruby regex search and replace array

来自分类Dev

Ruby REGEX解析器

来自分类Dev

Ruby Regex:拒绝选定的URL

来自分类Dev

Ruby Regex,拼接地址

来自分类Dev

Ruby Regex匹配意外字符

来自分类Dev

Ruby downcase method not working as expected

来自分类Dev

using grep linux command with perl regex + capturing groups

来自分类Dev

Ruby on Rails: Unable to retrieve regex from database

来自分类Dev

Ruby Regex-匹配文本列表

来自分类Dev

Ruby gsub regex意外行为

来自分类Dev

在Ruby中使用命名的Regex组

来自分类Dev

Ruby REGEX split, any issues with the code

来自分类Dev

Ruby + REGEX:验证电子邮件域

来自分类Dev

regex ruby for rack-ssl-enforcer

来自分类Dev

在Ruby中使用命名的Regex组

来自分类Dev

Ruby Regex *与字符序列不匹配

来自分类Dev

Ruby Regex-匹配文本列表

来自分类Dev

需要了解这个Ruby Regex代码

来自分类Dev

Ruby gsub regex意外行为