Does anyone have a regex in ruby that can match and replace a tab with 2 spaces?
Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A).
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus). If you're looking for common spacing, use "[ X]" or "[ X][ X]*" or "[ X]+" where X is the physical tab character (and each is preceded by a single space in all those examples).
Couldn't be simpler:
str.gsub(/\t/, ' ')
If you want to expand tabs (which is a slightly different task than replacing tabs), then:
# This algorithm by Brian Candler ([email protected]) 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"
The reason expanding tabs is different than just replacing them is that a tab can represent a different number of characters depending upon which column it appears in. For example, if the tab stops are every 8 columns, then a tab in the first column should be replaced by 8 spaces, but one in the second column by 7 spaces, one in the third column by 6 spaces, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With