powershell - 如何在Powershell中逐个字符串拆分

标签 powershell

我试图用一个分隔符来吐出字符串,它是一个字符串:

$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string.Split($separator)

作为 split 的结果,我得到:
5637144576, messag

est



5637145326, 1



5637145328, 0

代替
5637144576, messag<>est
5637145326, 1
5637145328, 0

当我尝试使用接受字符串 [] 的重载拆分时:
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = @("<<>>")
$string.Split($separator)

但我得到下一个错误:
Cannot convert argument "0", with value: "System.Object[]", for "Split" to type "System.Char[]": "Cannot convert value "<<>>" to type "System.Char". Error: "String must be exactly one character long.""

有人知道如何按字符串拆分字符串吗?

最佳答案

-split运算符使用字符串进行拆分,而不是像 Split() 这样的字符数组:

$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string -split $separator

5637144576, messag<>est
5637145326, 1
5637145328, 0

如果您想使用 Split()带有字符串的方法,您需要 $seperator是一个包含一个元素的字符串数组,并指定一个 stringsplitoptions 值。您可以通过检查其定义来看到这一点:
$string.Split

OverloadDefinitions                                                                                
-------------------                                                                                
string[] Split(Params char[] separator)                                                            
string[] Split(char[] separator, int count)                                                        
string[] Split(char[] separator, System.StringSplitOptions options)                                
string[] Split(char[] separator, int count, System.StringSplitOptions options)                     

#This one
string[] Split(string[] separator, System.StringSplitOptions options)      
string[] Split(string[] separator, int count, System.StringSplitOptions options)


$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = [string[]]@("<<>>")
$string.Split($separator, [System.StringSplitOptions]::RemoveEmptyEntries)

5637144576, messag<>est
5637145326, 1
5637145328, 0

编辑:正如@RomanKuzmin 指出的,-split默认情况下使用正则表达式模式进行拆分。所以请注意转义特殊字符(例如 . 在正则表达式中是“任何字符”)。您也可以强制simplematch禁用正则表达式匹配,如:
$separator = "<<>>"
$string -split $separator, 0, "simplematch"

阅读更多关于 -split here .

关于powershell - 如何在Powershell中逐个字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16435240/

相关文章:

powershell - 需要在PowerShell中的两种模式之间获取字符串

powershell - 不允许使用空管道元素

powershell - 无法从 32 位进程访问 Win32_WinSAT

powershell - 尝试在 Powershell 中登录 Azure

powershell - start-job 并行运行脚本

PowerShell相等运算符不是对称关系吗?

class - Powershell 类实现 get set 属性

internet-explorer - Powershell - 查看网站源信息

powershell - 在 PowerShell 中以 native 方式将字节写入文件

powershell - 访问脚本属性