Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, regex to match tabs and replace with 2 spaces?

Does anyone have a regex in ruby that can match and replace a tab with 2 spaces?

like image 481
AnApprentice Avatar asked Jan 17 '12 04:01

AnApprentice


People also ask

How do you match a tab in regex?

Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A).

What does =~ mean in Ruby regex?

=~ 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.

How do you match a space in regex?

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).


2 Answers

Couldn't be simpler:

str.gsub(/\t/, '  ')
like image 136
Joseph Silber Avatar answered Oct 21 '22 09:10

Joseph Silber


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.

like image 43
Wayne Conrad Avatar answered Oct 21 '22 08:10

Wayne Conrad