gpt4 book ai didi

regex - 如何在 Ruby 字符串中替换正则表达式之外的匹配项?

转载 作者:行者123 更新时间:2023-12-04 09:36:24 25 4
gpt4 key购买 nike

给定一个示例输入,如下所示:

s = "an example with 'one' word and 'two and three' words inside quotes"
我正在尝试遍历引号之外的部分以进行一些替换。例如转换 and&但只有在引号之外才能获得:
an example with 'one' word & 'two and three' words inside quotes
如果我要改变 的报价,我可以简单地执行以下操作:
s.gsub(/'.*?'/){ |q| q.gsub(/and/, '&') }
要得到:
an example with 'one' word and 'two & three' words inside quotes
我主要尝试了两件事来使这个策略适应 外面的报价。
首先,我首先尝试否定内部的正则表达式 gsub (即 /'.*?'/ )。我想如果有像 /v 这样的后缀修饰符我可以简单地做 s.gsub(/'.*?'/v){ ... } ,不幸的是我找不到这样的东西。有一个负面的前瞻(即 (?!pat) ),但我认为这不是我需要的。
其次,我尝试使用 splitgsub!像这样:
puts s.split(/'.*?'/){ |r| r.gsub!(/and/, '&') }
使用 split我可以遍历引号之外的部分:
s.split(/'.*?'/){ |r| puts r }
要得到:
an example with 
word and
words inside quotes
但是,我不能用 gsub 改变块内的这些部分。或 gsub! .我想我需要一个 split 的变异版本,类似于 gsubscan 的变异版本,但似乎没有这样的事情。
有没有一种简单的方法可以使这些方法中的任何一种起作用?

最佳答案

您可以使用以下正则表达式执行所需的替换。

r = /\G[^'\n]*?(?:'[^'\n]*'[^'\n]*?)*?\K\band\b/
Start your engine!
所需的 Ruby 代码如下。
str = "an and with 'one' word and 'two and three' words and end"

str.gsub(r, '&')
#=> "an & with 'one' word & 'two and three' words & end"
Ruby code tester
Ruby 的正则表达式引擎执行以下操作。本质上,正则表达式断言 "and"跟在自上次匹配之后的偶数个单引号之后,或者如果是第一次匹配,则跟在字符串开头的偶数个单引号之后。
\G          : asserts position at the end of the previous match
or the start of the string for the first match
[^'\n]*? : match 0+ chars other than ' and \n, lazily
(?: : begin capture group
'[^'\n]*' : match ' then 0+ chars other than ' and \n then '
[^'\n]*? : match 0+ chars other than ' and \n, lazily
) : end non-capture group
*? : execute non-capture group 0+ times, lazily
\K : forget everything matched so far and reset start of match
\band\b/ : match 'and'

关于regex - 如何在 Ruby 字符串中替换正则表达式之外的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62562571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com