RegEx после определенной строки - PullRequest
0 голосов
/ 15 марта 2019

У меня есть файл манифеста

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

Я хочу изменить значение Bundle-Name, используя -replace в Powershell. Я использовал этот шаблон Bundle-Name:(.*) Но он возвращается, включая имя пакета. Каким будет шаблон, если я хочу изменить только значение имени пакета?

1 Ответ

1 голос
/ 15 марта 2019

Вы можете захватить как 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...