Вы можете захватить как Bundle-Name:
, так и его значение в двух отдельных группах захвата.
Затем замените это так:
$manifest = @"
Bundle-ManifestVersion: 2
Bundle-Name: BundleSample
Bundle-Version: 4
"@
$newBundleName = 'BundleTest'
$manifest -replace '(Bundle-Name:\s*)(.*)', ('$1{0}' -f $newBundleName)
# or
# $manifest -replace '(Bundle-Name:\s*)(.*)', "`$1$newBundleName"
Выше приведено
Bundle-ManifestVersion: 2
Bundle-Name: BundleTest
Bundle-Version: 4
Детали регулярного выражения:
( Match the regex below and capture its match into backreference number 1
Bundle-Name: Match the character string “Bundle-Name:” literally (case sensitive)
\s Match a single character that is a “whitespace character” (any Unicode separator, tab, line feed, carriage return, vertical tab, form feed, next line)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
( Match the regex below and capture its match into backreference number 2
. Match any single character that is NOT a line break character (line feed)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
Благодаря LotPings , существует даже более простое регулярное выражение:
$manifest -replace '(?<=Bundle-Name:\s*).*', $newBundleName
Используется позитивный взгляд за спиной .
Детали регулярного выражения для этого:
(?<= Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
Bundle-Name: Match the characters “Bundle-Name:” literally
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)