如何在Powershell中逐个字符串拆分 [英] How to split string by string in Powershell
问题描述
我试图用一个分隔符来吐出字符串,这是一个字符串:
I'm trying to spit the string with a delimiter, which is a string:
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string.Split($separator)
作为分裂的结果,我得到:
As the result of splitting I get:
5637144576, messag
est
5637145326, 1
5637145328, 0
代替
5637144576, messag<>est
5637145326, 1
5637145328, 0
当我尝试使用接受 string[] 的重载拆分时:
When I try to use overloaded split which accepts string[]:
$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.""
有人知道如何按字符串拆分字符串吗?
Does someone knows how to split string by string?
推荐答案
-split
运算符使用字符串进行拆分,而不是像 Split()
这样的字符数组:
The -split
operator uses the string to split, instead of a chararray like Split()
:
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string -split $separator
5637144576, messag<>est
5637145326, 1
5637145328, 0
如果你想对字符串使用Split()
方法,你需要$seperator
是一个只有一个元素的stringarray,并且还要指定一个stringsplitoptions值.您可以通过检查其定义来看到这一点:
If you want to use the Split()
method with a string, you need the $seperator
to be a stringarray with one element, and also specify a stringsplitoptions value. You can see this by checking its definition:
$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
禁用正则表达式匹配,例如:
As @RomanKuzmin pointed out, -split
splits using regex-patterns by default. So be aware to escape special characters (ex. .
which in regex is "any character"). You could also force simplematch
to disable regex-matching like:
$separator = "<<>>"
$string -split $separator, 0, "simplematch"
阅读有关 -split
的更多信息此处.
Read more about -split
here.
这篇关于如何在Powershell中逐个字符串拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!