Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading