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
the result I am aiming for is:
abcd.V2.01
, so that the domain name ie 'contoso'
is dropped
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'
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 \\
- a \
char ([^\\.]*)
- Group 1 ( $1
): any zero or more chars other than \
and .
\.contoso
- a .contoso
string (\.V2[^\\]*)
- Group 2 ( $2
): .V2
string and then any zero or more chars other than \
$
- end of string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.