我试图用一个分隔符来吐出字符串,它是一个字符串:
$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/