Powershell provides string type methods to the string objects. Split
is one of them. Split method is used to split string into separate parts or a string array. In this tutorial we will look different usage types and examples of Split.
Powershell为字符串对象提供了字符串类型方法。 Split
就是其中之一。 拆分方法用于将字符串拆分为单独的部分或字符串数组。 在本教程中,我们将研究不同的用法类型和Split的示例。
指定分隔符 (Specify Separator)
While splitting a text or string we can provide a separator to split them. We will provide as argument to the split function. Function names are caseinsensitive. We will provide space as separator in this example.
在拆分文本或字符串时,我们可以提供一个分隔符来拆分它们。 我们将为split函数提供参数。 函数名称不区分大小写。 在此示例中,我们将提供空间作为分隔符。
$ "my test system is".split(" ")
Each separated element is printed in a new line.
每个分隔的元素都以新行打印。
使用多个分隔符拆分 (Split With Multiple Separators)
In some situations there may be more than one separator. Another useful feature of split function is we can specify multiple separators by adding more split functions and related separator in a string mode. In this example we will define two separator like space and point.
在某些情况下,可能会有多个分隔符。 拆分功能的另一个有用功能是,我们可以通过在字符串模式下添加更多拆分功能和相关的分隔符来指定多个分隔符。 在此示例中,我们将定义两个分隔符,例如space和point。
First we create our separator variable.
首先,我们创建分隔符变量。
$separators=(" ",".")
Then we provide $separators variable to the split function.
然后,我们将$ separators变量提供给split函数。
"my te.st sys.tem is".split($separators)
根据正则表达式拆分(Split According To Regex)
For more structured but complex strings and text regex based separator can be used. In this example we will use t
and s
characters as separator by specifying in regex.
对于更结构化但复杂的字符串和基于文本正则表达式的分隔符,可以使用。 在此示例中,我们将通过在正则表达式中指定使用t
和s
字符作为分隔符。
"my te.st sys.tem is".Split("[ts]")
分割Mac地址(Split Mac Address)
Another useful example will be splitting the mac address into hexadecimal parts.
另一个有用的示例是将mac地址拆分为十六进制部分。
"12-34-56-78-9A-BC".Split("-")
We get all parts of the mac address in a new line. If we need we can loop in them using for each.
我们在新行中获取mac地址的所有部分。 如果需要的话,可以将它们循环使用。
翻译自: https://www.poftut.com/powershell-split-string-operation-examples/