[英]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.