简体   繁体   English

使用正则表达式数组在 Ruby 中使用 `gsub` 转换字符串

[英]Transforming a string in Ruby w/ `gsub` using an array of regexps

I have a string, that I want to transform using Ruby's gsub and a TON of regexps and their resulting transformations in an array of arrays.我有一个字符串,我想使用 Ruby 的gsub和一吨正则表达式以及它们在数组数组中产生的转换进行转换。

I like to do something like this:我喜欢做这样的事情:

MY_REGEXPS = [
  [ 
    /^(\d-\d:) (SINGLE|DOUBLE|TRIPLE)/, 
    proc { "#{$1} #{$2.capitalize}," }
  ],
  #....Many for regexp/transformation pairs
]

my_string = "0:0 SINGLE (Line Drive, 89XD)"

MY_REGEXPS.inject(my_string) do |str, regexp_pair|
  str.gsub(regexp_pair.first, &regexp_pair.last)
end

However, the proc is not bound to the context of the gsub match, so variables like $1 and $2 are not available.但是,proc 未绑定到 gsub 匹配的上下文,因此$1$2等变量不可用。 I also confirm that if I just use the regexp/transformation in the process of a normal call to gsub, like:我还确认,如果我只是在正常调用 gsub 的过程中使用正则表达式/转换,例如:

my_string.gsub(/^(\d-\d:) (SINGLE|DOUBLE|TRIPLE)/) do
  "#{$1} #{$2.capitalize},"
end

the code works just fine.代码工作得很好。

Can anyone tell me a way for me to bind that proc to the context of the gsub so I can access $1 and $2 ?谁能告诉我一种将 proc 绑定到 gsub 上下文的方法,以便我可以访问$1$2

Thanks谢谢

Perhaps the following or a variant would meet your needs.也许以下或一个变体可以满足您的需求。

MY_REGEXPS = [
  [ 
    /^(\p{L}+) (\d:\d) (SINGLE|DOUBLE|TRIPLE) \1/i,
    proc { |_,v2,v3| "#{v2} #{v3.capitalize}," }
  ],
]

my_string = "dog 1:2 single dog (Line Drive, 89XD)"

MY_REGEXPS.inject(my_string) do |s,(re,p)|
  p.call(*s.match(re).captures)
end
  #=> "1:2 Single," 

I've included capture group #1 (\\p{L}+) (match one or more letters) to show how a capture group might be included that is not relevant to the proc calculation, but MatchData#captures can still be passed to the proc.我已经包含了捕获组 #1 (\\p{L}+) (匹配一个或多个字母)以显示如何包含与 proc 计算无关的捕获组,但MatchData#captures仍然可以传递给过程。 (Capture group #1 is used here to ensure that the content of that capture group appears again at the specified location in the string ( \\1 )). (此处使用捕获组 #1 以确保该捕获组的内容再次出现在字符串 ( \\1 ) 中的指定位置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM