简体   繁体   English

同时更换2个字符串?

[英]Replace 2 strings at the same time?

how can I replace 2 strings in the same time? 如何在同一时间更换2个字符串? for example let's say I have string like this: 例如,假设我有这样的字符串:

str1 = "AAAA BBBB CCCC DDDD" str1 =“AAAA BBBB CCCC DDDD”

i want to replace every "AAAA" with "CCCC" and every "CCCC" with "AAAA" but if i did: 我想用“CCCC”取代每个“AAAA”,用“AAAA”取代每个“CCCC”,但如果我这样做:

str1.gsub("AAAA","CCCC") # CCCC BBBB CCCC DDDD str1.gsub(“AAAA”,“CCCC”)# CCCC BBBB CCCC DDDD

str1.gsub("CCCC","AAAA") # AAAA BBBB AAAA DDDD str1.gsub(“CCCC”,“AAAA”)# AAAA BBBB AAAA DDDD

what I want str1 to be " CCCC BBBB AAAA DDDD" 我想要str1成为“ CCCC BBBB AAAA DDDD”

General answer: 一般答案:
Use a regex to match both AAAA and CCCC, then substitute each match with CCCC and AAAA respectively. 使用正则表达式匹配AAAA和CCCC,然后分别用CCCC和AAAA替换每个匹配。

edit to clear up the confusion 编辑以消除混乱

str1.gsub(/(AAAA|CCCC)/) { $1 == 'AAAA' ? 'CCCC' : 'AAAA' }

edit i thought of a more elegant way too :) 编辑我想到了更优雅的方式:)

str1.gsub(/((AAAA)|(CCCC))/) { $2 ? 'CCCC' : 'AAAA' }

Is it an option for you to replace AAAA with something else first and then proceed? 您可以选择先用其他东西替换AAAA,然后继续吗?

str1.gsub("AAAA","WXYZ") # WXYZ BBBB CCCC DDDD
str1.gsub("CCCC","AAAA") # WXYZ BBBB AAAA DDDD
str1.gsub("WXYZ","CCCC") # CCCC BBBB AAAA DDDD

A solution (although something based around regex would be best) would be something along the lines of creating a replacement hash as such, which can be extended as needed. 一个解决方案(虽然基于正则表达式的东西是最好的)将像创建替换哈希一样,可以根据需要进行扩展。 I just quickly put this together to demonstrate. 我只是很快就把它们放在一起来展示。 I'm sure with a bit more love and care you can come up with something more elegant that works along the same lines as this implementation only works for strings with spaces. 我肯定会有更多的爱和关心,你可以想出一些更优雅的东西,它们的工作方式相同,因为这个实现只适用于带空格的字符串。

str1 = "AAAA BBBB CCCC DDDD"    
replacements = { "AAAA" => "CCCC", "CCCC" => "AAAA", "XXXX" => "ZZZZ" } # etc...

new_string = ""
str1.split(" ").each do |s| 
    new_string += replacements[s] || s
    new_string += " "
end

puts new_string # CCCC BBBB AAAA DDDD 

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

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