.net 如何在 PowerShell 中将字符串内容拆分为字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17028419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string content into an array of strings in PowerShell?
提问by pencilCake
I have a string that has email addresses separated by semi-colon:
我有一个字符串,其中的电子邮件地址以分号分隔:
$address = "[email protected]; [email protected]; [email protected]"
How can I split this into an array of strings that would result as the following?
如何将其拆分为如下结果的字符串数组?
[string[]]$recipients = "[email protected]", "[email protected]", "[email protected]"
回答by Mike Zboray
As of PowerShell 2, simple:
从 PowerShell 2 开始,简单:
$recipients = $addresses -split "; "
Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplitto force case-sensitivity. See about_Splitfor more details.
请注意,右侧实际上是一个不区分大小写的正则表达式,而不是简单的匹配。使用csplit武力区分大小写。有关更多详细信息,请参阅about_Split。
回答by Shay Levy
[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)
回答by user2453734
Remove the spaces from the original string and split on semicolon
从原始字符串中删除空格并用分号分割
$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')
Or all in one line:
或者全部在一行中:
$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')
$addressesbecomes:
$addresses变成:
@('[email protected]','[email protected]','[email protected]')

