Bra*_*ady 3 ruby regex ruby-on-rails-3
我需要基于对字符串的正则表达式搜索来替换db字段中的一些文本.
到目前为止,我有这个:
foo = my_string.gsub(/\[0-9\]/, "replacement" + array[#] + "text")
Run Code Online (Sandbox Code Playgroud)
所以,我在现场搜索括号括起来的数字的每个实例([1],[2]等).我想要做的是在搜索中找到每个数字(在括号内),并使用该数字来查找特定的数组节点.
有任何想法吗?如果有人需要任何澄清,请告诉我.
最简单的方法是使用块形式gsub:
foo = my_string.gsub(/\[(\d+)\]/) { array[$1.to_i] }
Run Code Online (Sandbox Code Playgroud)
并注意正则表达式中的捕获组.在块内,全局$1是第一个捕获组匹配的.
您也可以使用命名捕获组,但这需要不同的全局,因为$~(AFAIK)是获取MatchData块内当前对象的唯一方法:
foo = my_string.gsub(/\[(?<num>\d+)\]/) { |m| a[$~[:num].to_i] }
Run Code Online (Sandbox Code Playgroud)
例如:
>> 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?"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3576 次 |
| 最近记录: |