简体   繁体   中英

Trim or replace PowerShell string variable

I have a string variable that holds the following information

@{EmailAddress=test1@tenant.onmicrosoft.com},@{EmailAddress=test2@tenant.onmicrosoft.com}

I am using this variable for a cmdlet that only accepts data in the format of

test1@tenant.onmicrosoft.com, test2@tenant.onmicrosoft.com

I have tried TrimStart("@{EmailAddress=") but this only removes @{EmailAddress= for the first user and I guess TrimEnd would not be much use as I presume that it is due to the fact it reading the string as one line and not as user1,user2 etc.

Would anyone be able to provide advice on how to remove these unwanted characters.

A possible solution is to use Regex to extract the strings that you want, and combine them into a result:

$str = "@{EmailAddress=test1@tenant.onmicrosoft.com},@{EmailAddress=test2@tenant.onmicrosoft.com}"
$pattern = [regex]'@{EmailAddress=(.+?)}'
$result = ($pattern.Matches($str) | % {$_.groups[1].value}) -join ','

$result then is:

test1@tenant.onmicrosoft.com,test2@tenant.onmicrosoft.com

Another solution would be to use the -replace function. This is just a one-liner:

'@{EmailAddress=test1@tenant.onmicrosoft.com},@{EmailAddress=test2@tenant.onmicrosoft.com}' -replace '@{EmailAddress=([^}]+)}.*?', '$1'

Regex used to replace:

在此处输入图片说明

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.

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