如何在 PowerShell 中按单词拆分字符串?
今天,我想在 PowerShell 中做一个不同的分割字符串的例子。在本教程中,我将通过完整的脚本和示例向您展示如何在 PowerShell 中按单词拆分字符串。
在 PowerShell 中按单词拆分字符串
现在,让我们检查一下在 PowerShell 中按单词分割字符串的各种方法。
方法 1:对特定单词使用 -split 运算符
PowerShell 中的 -split 运算符可以与特定单词一起用作分隔符。
这是一个完整的例子:
$string = "United States is a beautiful country"
$delimiter = "beautiful"
$parts = $string -split $delimiter
$parts在此示例中,使用单词 “beautiful” 作为分隔符将字符串 “United States is a beautiful Country” 拆分为一个数组。输出将是:
United States is a
country
我执行了上面的 PowerShell 脚本,您可以在下面的屏幕截图中看到输出:
方法 2:对特定单词使用 .Split() 方法
.NET 中的 .Split() 方法还可用于在 PowerShell 中按特定单词拆分字符串。但是,此方法需要将字符串转换为字符数组。
这是一个例子:
$string = "United States is a beautiful country"
$delimiter = "beautiful"
$parts = $string -split $delimiter
$parts在此示例中,使用单词 "beautiful" 作为分隔符来分割字符串。输出将是:
United States is a
country执行代码后,您可以在下面的屏幕截图中看到输出:
阅读如何在 PowerShell 中按换行符拆分字符串?
方法 3:使用正则表达式和 -split
PowerShell 的 -split 运算符可以与正则表达式一起使用来按单词拆分字符串。如果分隔符单词以不同的形式出现(例如,不区分大小写),这可能很有用。
示例:
$string = "United States is a beautiful country"
$delimiter = "beautiful"
$parts = $string -split "($delimiter)"
$parts
在此示例中,正则表达式 ($delimiter) 用于按单词 "beautiful" 分割字符串。输出将是:
United States is a
country方法 4:使用 -replace 和 -split
在 PowerShell 中,您还可以使用 -replace 运算符将特定单词替换为唯一字符或字符串,然后使用 -split 运算符。
示例:
$string = "United States is a beautiful country"
$delimiter = "beautiful"
$string = $string -replace $delimiter, "|"
$parts = $string -split "\|"
$parts在此示例中,单词 "beautiful" 被替换为竖线字符 |,然后字符串被 | 分割。输出将是:
United States is a
country阅读在 PowerShell 中的字符串中添加双引号
方法 5:使用 Select-String 和 -match
您还可以使用 Select-String 和 -match 在 PowerShell 中提取特定单词之前和之后的字符串部分。
示例:
$string = "United States is a beautiful country"
$delimiter = "beautiful"
if ($string -match "(.*)$delimiter(.*)") {
$before = $matches[1]
$after = $matches[2]
}
$before
$after该脚本使用正则表达式模式来捕获单词“beautiful”之前和之后的所有内容。输出将是:
United States is a
country您可以看到下面的屏幕截图:
结论
在本 PowerShell 教程中,我解释了如何在 PowerShell 中按单词拆分字符串,使用各种方法,例如:
- 将 -split 运算符与特定单词一起使用
- 对特定单词使用 .Split() 方法
- 将正则表达式与 -split 一起使用
- 使用 -replace 和 -split
- 使用 Select-String 和 -match


