Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby正则表达式中的变量_Ruby_Regex_String - Fatal编程技术网

Ruby正则表达式中的变量

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

我有一个变量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/#{$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应该可以工作。谢谢,这样效果更好:-