某些字符串后的RegEx

时间:2019-03-15 06:46:35

标签: regex string powershell text

我有一个清单文件

Bundle-ManifestVersion: 2
Bundle-Name: BundleSample
Bundle-Version: 4

我想在Powershell中使用-replace更改Bundle-Name的值。 我使用了这种模式Bundle-Name:(.*) 但是它返回包括Bundle-Name。如果我只想更改Bundle-Name的值,那将是什么模式?

1 个答案:

答案 0 :(得分:1)

您可以在两个单独的捕获组中捕获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

这使用了positive lookbehind

该正则表达式的详细信息是:

(?<=                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)