2013-09-05 33 views
0

我正在解析来自XML转储的维基文本,其中包含一些名为'section'的字符串,其中包含双花括号中的模板,包括一些我想要重新组织的参数。在Ruby中用gsub替换扫描:如何在gsub块中允许代码?

这有一个例子名为TextTerm:

section="Sample of a text with a first template {{TextTerm|arg1a|arg2a|arg3a...}} and then a second {{TextTerm|arg1b|arg2b|arg3b...}} etc." 

我可以使用scan和正则表达式使用来获得每个模板和它的工作在一个循环:

section.scan(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/i).each { |item| puts "1=" + item[1] # arg1a etc.} 

而且,我一直能够提取模板的第一个参数的数据库。

现在我还想要替换模板“NewTextTerm”的名称,并通过将第二个参数放在第一个参数的位置来重新组织它的参数。

我可以在同一个循环中完成吗?例如,通过由gsub(rgexp){ block}改变scan

section.gsub!(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/) { |item| '{{NewTextTerm|\2|\1}}'} 

我得到:

"Sample of a text with a first template {{NewTextTerm|\\2|\\1}} and then a second {{NewTextTerm|\\2|\\1}} etc." 

这意味着正则表达式的参数无法识别。即使它有效,我想在gsub区块内有一些位置来处理这些参数。例如,块中的puts类似于scan().each块,但不能包含puts块,但只有一个要替换的字符串。

欢迎任何想法。

PS:一些编辑:大括号和“section = added”,代码是完整的。

+0

这个评论应该是一个答案,所以它可以适当地upvoted。 – DNNX

+0

你的意思是双**括号或双**括号**? – sawa

+0

显示您的代码的完整示例,而不是单行。在短循环中处理整个问题可能有更好的方法,但是如果没有看到你的代码,我们就不知道你设置了什么。因此,我们可以建议逐步改进,但我们可能会提出更好的建议。我们还需要查看您正在处理的大量文本样例:是否重复使用了{{...}}块,并在整个文件中使用了相同的标记集?编写模板处理引擎并不难,但我们需要更好的信息。 –

回答

0

当你更换新字符串参数,你可以使用'\1'等这样的:

string.gsub!(regex, '...\1...\2...') 

当你更换新的模块,你可以使用"#$1"等这样的:

string.gsub!(regex){"...#$1...#$2..."} 

您正在混合使用。坚持任何一个。

0

是的,用双引号改变引用是不够的,#1是答案。这里是完整的代码:

section="Sample of a text with a first template {{TextTerm|arg1a|arg2a|arg3a...}} and then a second {{TextTerm|arg1b|arg2b|arg3b...}} etc." 
section.gsub(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/) { |item| "{{New#$1|#$3|#$2}}"} 
"Sample of a text with a first template {{NewTextTerm|arg2a|arg3a...|arg1a}} and then a second {{NewTextTerm|arg2b|arg3b...|arg1b}} etc." 

因此,它的工作原理。谢谢。

但现在我有一个 “功能” 来替换字符串,返回改变的字符串:

def stringreturn(arg1,arg2,arg3) strr = "{{New"+arg1 + arg3 +arg2 + "}}"; return strr ; end 

section.gsub(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/) { |item| stringreturn("#$1","|#$2","|#$3") } 

将返回:

"Sample of a text with a first template {{NewTextTerm|arg2a|arg3a...|arg1a}} and then a second {{NewTextTerm|arg2b|arg3b...|arg1b}} etc." 

感谢所有! 可能有更好的方法来使用Ruby在MediaWiki模板中操作参数。