ruby正则表达式替换相应的字符串

时间:2014-03-03 08:08:37

标签: ruby regex string

str = "1627207:132069:color:green;20518:28421:size:62cm"

aliastr = "20518:28421:S;20518:28358:L;20518:28357:M;1627207:132069:red"

如何动态替换str为“1627207:132069:color:red; 20518:28421:size:S”。

2 个答案:

答案 0 :(得分:0)

这是一个非常不明确的问题,但我想我现在就明白了。您的aliastr包含控制替换的映射,即键'20518:28421:'应映射到值'S',键'1627207:132069:'应映射到'红色'。然后,您要在str中搜索这些键,并将其当前值替换为该新值。这样做:

str = "1627207:132069:color:green;20518:28421:size:62cm"
aliastr = "20518:28421:S;20518:28358:L;20518:28357:M;1627207:132069:red"

mapping = Hash[aliastr.scan(/(\d+:\d+:)(.*?)(?:;|$)/)]
# mapping = {"20518:28421:"=>"S", "20518:28358:"=>"L", "20518:28357:"=>"M", "1627207:132069:"=>"red"}

replaced = str.gsub(/(\d+:\d+:)(\w+:).*?(;|$)/) do |match|
  key = $1
  value = mapping[$1]
  key + $2 + value + $3
end

p replaced
# => "1627207:132069:color:red;20518:28421:size:S"

答案 1 :(得分:0)

您的问题不是很清楚,可能包含错误(想要的结果中的“颜色:红色”与aliastr中的“红色”)。

您可以尝试这样的事情:

str = "1627207:132069:color:green;20518:28421:size:62cm"
aliastr = "20518:28421:S;20518:28358:L;20518:28357:M;1627207:132069:red"
replacements = aliastr.split(";").map{|s| parts=s.split(":"); [/#{parts[0]}:#{parts[1]}:.*/,s]}
src = str.split(";")
src.map{|s| replacements.each{|r| s.sub!(r[0],r[1])}; s }.join(";")