有人在Ruby中有一个可以匹配并将制表符替换为2个空格的正则表达式吗?
有人在Ruby中有一个可以匹配并将制表符替换为2个空格的正则表达式吗?
再简单不过了:
str.gsub(/\t/, ' ')
# This algorithm by Brian Candler (B.Candler@pobox.com) found on the
# org.ruby-lang.ruby-talk mailing list
# http://markmail.org/message/avdjw34ahxi447qk
# Date: 2003-5-31 13:35:09
# Subject: Re: expandtabs
def expand_tabs(s, tab_stops = 8)
s.gsub(/([^\t\n]*)\t/) do
$1 + " " * (tab_stops - ($1.size % tab_stops))
end
end
p expand_tabs("\tfoo", 2) # => " foo"
p expand_tabs(" \tfoo", 2) # => " foo"
p expand_tabs("\t\tfoo", 2) # => " foo"