Search code examples
regexrubypcre

Replace N spaces at the beginning of a line with N characters


I am looking for a regex substitution to transform N white spaces at the beginning of a line to N  . So this text:

list:
  - first

should become:

list:
  - first

I have tried:

str = "list:\n  - first"
str.gsub(/(?<=^) */, "&nbsp;")

which returns:

list:
&nbsp;- first

which is missing one &nbsp;. How to improve the substitution to get the desired output?


Solution

  • Use gsub with a callback function:

    str = "list:\n  - first"
    output = str.gsub(/(?<=^|\n)[ ]+/) {|m| m.gsub(" ", "&nbsp;") }
    

    This prints:

    list:
    &nbsp;&nbsp;- first
    

    The pattern (?<=^|\n)[ ]+ captures one or more spaces at the start of a line. This match then gets passed to the callback, which replaces each space, one at a time, with &nbsp;.