1

I'm using the .Replace() function to replace line feeds in the file I'm working on with a carriage return and a line feed but I would also like to match any number of spaces preceding the line feed. Can this be done in the same operation using a regular expression?

I've tried various combinations of "\s +*" but none have worked, except with a fixed number of manually typed spaces.

This version works for the one space case:

.Replace(" `n","`r`n")

For example, a file like this:

...end of line one\n
...end of line two   \n

would look like:

...end of line one\r\n
...end of line two\r\n
Stacey
  • 81
  • 2
  • 9

1 Answers1

2

The .Replace() method of the .NET [string] type performs literal string replacements.

By contrast, PowerShell's -replace operator is based on regexes (regular expressions), so it allows you to match a variable number of spaces (including none) with  *:

"...end of line two    `n" -replace ' *\n', "`r`n"
mklement0
  • 382,024
  • 64
  • 607
  • 775