1

I'm trying to replace a string with another string and also add a line-break character, but I can't figure out the correct syntax. Here's a simplified example:

'first@second' -replace ('(fi.*t)@', "$1`n")

Result:

second

I then tried:

'first@second' -replace ('(fi.*t)@', '$1`n')

Result:

first`nsecond

It looks I can either have a line-break or a back-reference, but not both. What do I need to change to get both? What I want is:

first
second
Nemo XXX
  • 644
  • 2
  • 14
  • 35
  • 3
    No, you can have both. ``'first@second' -replace ('(fi.*t)@', "`$1`n")``. Or `'$1'+"`n"` – Wiktor Stribiżew Sep 23 '21 at 11:38
  • Terminology note: A [_backreference_](https://learn.microsoft.com/en-us/dotnet/standard/base-types/backreference-constructs-in-regular-expressions) is a _pure regex feature_ for referencing a group that matched earlier _in the same regex_ (e.g, `\1`). While conceptually related, a [_capture-group substitution_](https://learn.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions#substituting-a-numbered-group) (e.g. `$1`) applies only to (regex-based) _string substitution_ operations. – mklement0 Sep 23 '21 at 17:47
  • An aside re syntax: The parentheses in `'...' -replace ('...', '...')` are unnecessary (this applies to all PowerShell operators with multiple RHS operands, such as `-split`). – mklement0 Sep 24 '21 at 15:59

0 Answers0