繁体   English   中英

在使用正则表达式匹配模式后排除 substring

[英]Exclude a substring after a pattern is matched using regex

我想编写一个拆分字符串的正则表达式,例如只选择几个元素。 例如: 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'

您可以使用两个捕获组:

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

不要忘记在正则表达式模式中转义文字点。 这是上述正则表达式的演示 详情

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM