gpt4 book ai didi

ruby - 正则表达式替换 Ruby on Rails 中的表达式

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:03 25 4
gpt4 key购买 nike

我需要根据对字符串的正则表达式搜索来替换数据库字段中的一些文本。

到目前为止,我有这个:

foo = my_string.gsub(/\[0-9\]/, "replacement" + array[#] + "text")

因此,我正在现场搜索用方括号([1]、[2] 等)括起来的数字的每个实例。我想做的是在搜索中找到每个数字(在括号内),并使用该数字来查找特定的数组节点。

有什么想法吗?让我知道是否有人需要任何澄清。

最佳答案

最简单的方法是使用 gsub 的 block 形式:

foo = my_string.gsub(/\[(\d+)\]/) { array[$1.to_i] }

并注意正则表达式中的捕获组。在 block 内,全局 $1 是第一个捕获组匹配的内容。

您也可以使用命名的捕获组,但这需要不同的全局,因为 $~ 是(据我所知)获取当前 MatchData 对象的唯一方法 block :

foo = my_string.gsub(/\[(?<num>\d+)\]/) { |m| a[$~[:num].to_i] }

例如:

>> s = 'Where [0] is [1] pancakes [2] house?'
=> "Where [0] is [1] pancakes [2] house?"
>> a = %w{a b c}
=> ["a", "b", "c"]

>> s.gsub(/\[(\d+)\]/) { a[$1.to_i] }
=> "Where a is b pancakes c house?"

>> s.gsub(/\[(?<num>\d+)\]/) { |m| a[$~[:num].to_i] }
=> "Where a is b pancakes c house?"

关于ruby - 正则表达式替换 Ruby on Rails 中的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278816/

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