我希望在 PowerShell 中运行长字符串句子,并在每 32 个字符+空格后返回一个新行(以避免在单词中间添加新行)。这是我迄今为止尝试过的:
$Runonsentence = 'Interestingly, Bryan A. Garners "The Oxford Dictionary of American Usage and Style" states that while there is a distinction between run-on sentences and comma splices, it isnt typically noteworthy. However, Garner also adds "The distinction can be helpful in differentiating between the wholly unacceptable (true run-on sentences) and the usually-but-not-always unacceptable (comma splices).'
Filter Get-Stringy {
for($num = 0; $num -le $_.Length-32; $num+=32) {
$indexer = $_.Substring($num, 32)
$parser = $indexer.LastIndexOf(" ", 32)
$trimmer = $indexer.Split($parser)
$trimmer.Trim()
}
}
$Runonsentence | Get-Stringy
这是它返回的内容:
Interestingly, Bryan A. Garners
"The Oxford Dictionary of Americ
an Usage and Style" states that
while there is a distinction bet
ween run-on sentences and comma
splices, it isnt typically notew
orthy. However, Garner also adds
"The distinction can be helpful
in differentiating between the
wholly unacceptable (true run-on
sentences) and the usually-but-
not-always unacceptable (comma s
正如您从上面的结果中可能看到的那样,末尾的单词被截断,并且整个字符串没有被遍历或显示。如果有不同的策略或方法来做到这一点,我们将不胜感激!
最佳答案
使用“-replace”运算符尝试以下正则表达式模式。
由于正则表达式默认是贪婪的,因此它将首先尝试获取 32 个字符 + 空格,然后将数量减少到 0。(大括号内定义的所有内容:{0,32})
为了避免在每行后面出现空格,我使用了组结构,并且只返回第一个组“$1”
$Runonsentence = 'Interestingly, Bryan A. Garners "The Oxford Dictionary of American Usage and Style" states that while there is a distinction between run-on sentences and comma splices, it isnt typically noteworthy. However, Garner also adds "The distinction can be helpful in differentiating between the wholly unacceptable (true run-on sentences) and the usually-but-not-always unacceptable (comma splices).'
$Runonsentence -replace '(.{0,32})(?:\s+|$)', "`$1`r`n"
不要忘记替换部分中的转义字符。我们不需要 PowerShell 变量 $1。所以使用`$1
关于regex - 在 PowerShell 字符串中的 32 个字符 + 空格后返回新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64832524/