Ruby正则表达式中的变量
我有一个变量titel,其中包含一些文章的标题名。在给定的*.ent文件XML Entities中,我有一个字符串|您需要更改de de/TITEL.ent文件中的HOLDER实体|,我想用MyCompany替换它 所以我试着:Ruby正则表达式中的变量,ruby,regex,string,Ruby,Regex,String,我有一个变量titel,其中包含一些文章的标题名。在给定的*.ent文件XML Entities中,我有一个字符串|您需要更改de de/TITEL.ent文件中的HOLDER实体|,我想用MyCompany替换它 所以我试着: text = File.read("#{$titel}/de-DE/#{$titel.ent}") new_contents = text.gsub(/"| You need to change the HOLDER entity in the de-DE/#{$tit
text = File.read("#{$titel}/de-DE/#{$titel.ent}")
new_contents = text.gsub(/"| You need to change the HOLDER entity in the de-DE/#{$titel}.ent file |"/, "XCOM AG")
puts new_contents
File.open("#{$titel}/de-DE/#{$titel.ent}", "w") { |file| file.puts new_contents}
现在它说它不是有效代码。
也许我必须更改正则表达式中的任何内容?正则表达式文本使用/作为分隔符:
text.gsub(/"| You need to change the HOLDER entity in the de-DE/#{$titel}.ent file |"/, "XCOM AG")
# ^ ^
# start end
要在正则表达式中使用分隔符或元字符,必须对其进行反斜杠转义,即/beans\/,|beans\|等:
text.gsub(/\| You need to change the HOLDER entity in the de-DE\/#{$titel}\.ent file \|/, "XCOM AG")
我还删除了regexp中的引号
但如前所述,您可以使用字符串:
text.gsub("| You need to change the HOLDER entity in the de-DE/#{$titel}.ent file |", "XCOM AG")
为什么要使用正则表达式?new_contents=text.gsub|您需要更改de/{$titel}.ent文件|中的HOLDER实体,XCOM AG应该可以工作。谢谢,这样效果更好:-