【问题标题】:RegEx after certain string某个字符串后的正则表达式
【发布时间】:2019-08-06 04:54:51
【问题描述】:

我有一个清单文件

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

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

【问题讨论】:

标签: regex string powershell text


【解决方案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)

【讨论】:

  • 使用lookbehind $manifest -replace '(?&lt;=Bundle-Name: ).*',$newBundleName 更容易
  • @LotPings 是的,这很漂亮。我已将您的正则表达式添加到答案中。希望你不要介意。
猜你喜欢
  • 2017-11-24
  • 2018-11-30
  • 2019-11-09
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
  • 2011-08-13
相关资源
最近更新 更多