问题
I currently have a list of 25,000+ server names. Each name has a ton of extra stuff added on to the name, which I want to remove. Here is a sample data:
WindowsAuthServer @{htew804WIN}
I want to remove "WindowsAutherServer @{" and "WIN}" from each server, leaving just "htew804" left. I currently have:
$remove1 = $file -remove "WindowsAutherServer @{",""
$final = $remove1 -remove "WIN}",""
This works, but I would like to do it all in one step if possible. Can this be done?
回答1:
This RegEx could do it in one go:
$str = "WindowsAuthServer @{htew804WIN}"
$str -replace '.*?{(.*?)WIN}','$1'
回答2:
Think about what you want to keep instead.
"WindowsAuthServer @{htew804WIN}" | foreach { $x = $_ -match '\@\{(.+)WIN}' ; $Matches[1] }
回答3:
This can easily be done using String.Substring() and String.LastIndexOf() methods:
$str = "WindowsAuthServer @{htew804WIN}"
$str.Substring(($open = $str.LastIndexOf('{') + 1), $str.LastIndexOf('}') - $open - 3)
We first use String.LastIndexOf('{') to find the last occurrence of {, then (using that as an offset) calculate the length until just before WIN}
回答4:
Or this one:
$str = "WindowsAuthServer @{htew804WIN}"
([regex]'@\{(\w+)WIN\}').Match($str).Groups[1].Value;
来源:https://stackoverflow.com/questions/53834831/how-to-remove-multiple-items-at-once