【问题标题】:Exclude a substring after a pattern is matched using regex使用正则表达式匹配模式后排除子字符串
【发布时间】:2022-01-03 09:26:29
【问题描述】:

我想编写一个拆分字符串的正则表达式,例如只选择几个元素。例如: M:\Shares\Profiles\Server\Profiles\abcd.contoso.V2.01

我的目标是:

abcd.V2.01,这样就去掉了'contoso'这个域名

但是,在找到匹配项后,我无法排除部分字符串。我试过了

$original = 'M:\Shares\Profiles\Server\Profiles\abcd.contoso.V2.01'
$modified = $original -replace '.*\\([^\\.]+.contoso.V2)[^\\]*$', '$1'

返回 $modified'abcd.contoso.V2'

【问题讨论】:

  • 如果你要替换的东西是一个常数,那么这个 >>> 'M:\Shares\Profiles\Server\Profiles\abcd.contoso.V2.01'.Split('\')[-1] -replace '\.contoso'

标签: regex powershell


【解决方案1】:

您可以使用两个捕获组:

$original = 'M:\Shares\Profiles\Server\Profiles\abcd.contoso.V2.01'
$original -replace '.*\\([^\\.]*)\.contoso(\.V2[^\\]*)$', '$1$2'
# => abcd.V2.01

不要忘记在正则表达式模式中转义文字点。这是demo of the above regex详情

  • .* - 除 LF 字符外的任何零个或多个字符
  • \\ - 一个 \ 字符
  • ([^\\.]*) - 第 1 组 ($1):除 \. 之外的任何零个或多个字符
  • \.contoso - .contoso 字符串
  • (\.V2[^\\]*) - 第 2 组 ($2):.V2 字符串,然后是除 \ 之外的任何零个或多个字符
  • $ - 字符串结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 2022-07-28
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多