给出以下缩进文本:
two spaces
four
six
non-leading spaces
我想将每两个前导空格转换为一个标签,实际上是从软标签转换为硬标签。我正在寻找以下结果(使用'x'代替“\ t”):
xtwo spaces
xxfour
xxxsix
non-leading spaces
在ruby中执行此操作的最有效或最有说服力的方法是什么?
到目前为止我的工作似乎有效,但感觉不对。
input.gsub!(/^ {2}/,"x")
res = []
input.split(/\n/).each do |line|
while line =~ /^x+ {2}/
line.gsub!(/^(x+) {2}/,"\\1x")
end
res << line
end
puts res.join("\n")
我注意到answer使用了sed和\ G:
perl -pe '1 while s/\G {2}/\t/gc' input.txt >output.txt
但我无法弄清楚如何模仿Ruby中的模式。这是我得到的:
rep = 1
while input =~ /^x* {2}/ && rep < 10
input.gsub!(/\G {2}/,"x")
rep += 1
end
puts input
答案 0 :(得分:4)
在多行模式下使用(?:^ {2})|\G {2}
有什么问题?
第一场比赛将始终在线的开头,
然后\ G将紧接着匹配,或匹配
将失败。下一场比赛将始终是该线的开头..重复。
在Perl中$str =~ s/(?:^ {2})|\G {2}/x/mg;
或$str =~ s/(?:^ {2})|\G {2}/\t/mg;
input.gsub!(/(?:^ {2})|\G {2}/m,"x")
编辑:当然可以将锚点分解出来并进行轮换 http://ideone.com/1oDOJ
input.gsub!(/(?:^|\G) {2}/m,"x")
答案 1 :(得分:2)
您可以使用单个gsub:
str.gsub(/^( {2})+/) { |spaces| "\t" * (spaces.length / 2) }