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(/(?<=^) */, " ")
which returns:
list:
- first
which is missing one
. How to improve the substitution to get the desired output?
Use gsub
with a callback function:
str = "list:\n - first"
output = str.gsub(/(?<=^|\n)[ ]+/) {|m| m.gsub(" ", " ") }
This prints:
list:
- 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
.