简体   繁体   English

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

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

I want to write a regex that splits a string such as only few elements are selected.我想编写一个拆分字符串的正则表达式,例如只选择几个元素。 For example: M:\Shares\Profiles\Server\Profiles\abcd.contoso.V2.01例如: M:\Shares\Profiles\Server\Profiles\abcd.contoso.V2.01

the result I am aiming for is:我的目标是:

abcd.V2.01 , so that the domain name ie 'contoso' is dropped abcd.V2.01 ,以便删除域名,即'contoso'

However, I am unable to exclude a part of the string after a match is found.但是,找到匹配项后,我无法排除字符串的一部分。 I tried我试过了

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

that returns $modified as 'abcd.contoso.V2'返回$modified'abcd.contoso.V2'

You can use two capturing groups:您可以使用两个捕获组:

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

Do not forget to escape literal dots in the regex pattern.不要忘记在正则表达式模式中转义文字点。 Here is a demo of the above regex .这是上述正则表达式的演示 Details :详情

  • .* - any zero or more chars other than LF chars .* - 除 LF 字符外的任何零个或多个字符
  • \\ - a \ char \\ - 一个\字符
  • ([^\\.]*) - Group 1 ( $1 ): any zero or more chars other than \ and . ([^\\.]*) - 第 1 组 ( $1 ):除\和 . 之外的任何零个或多个字符.
  • \.contoso - a .contoso string \.contoso - 一个.contoso字符串
  • (\.V2[^\\]*) - Group 2 ( $2 ): .V2 string and then any zero or more chars other than \ (\.V2[^\\]*) - 第 2 组 ( $2 ): .V2字符串,然后是除\之外的任何零个或多个字符
  • $ - end of string. $ - 字符串结束。

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

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