Reputation: 1641
I have a problem when replacing a multi line string with the MultiLine option.
I'd expect the following snippet:
@"
abc
---
def
"@ -replace '(?m)^---$', 'AAA'
to result in:
abc
AAA
def
whereas it outputs:
abc
---
def
Why it doesn't work?
Upvotes: 0
Views: 239
Reputation: 33
You need to use multiline mode also for the new line:
@"
abc
---
def
"@ -replace '(?m)^---(?m)$', 'AAA'
Upvotes: 0
Reputation: 864
The end of line/string token $
of regex can't match the end of line in regex' multiline mode when CRLF (carriage return 0x0D + line feed 0x0A) is used for line breaks.
Info: This is not the case in non-multiline mode where $
matches the end of string.
For files which are using CRLF as line endings (which is the default behavior of Windows) it's necessary to use \r$
, but to be entirely compatible with any file and operating system (like unix/linux, where LF is used), the carriage return should be made optional: \r?$
With PowerShell it's also easily possible to figure out which line endings are in place. The character hex code 0D
followed by 0A
means CRLF.
Example:
@'
TEST
123
'@ | Format-Hex
#returns:
#
# Label: String (System.String) <7AFCD388>
#
# Offset Bytes Ascii
# 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
# ------ ----------------------------------------------- -----
# 0000000000000000 54 45 53 54 0D 0A 31 32 33 TEST��123
Upvotes: 1