regex - 在 PowerShell 字符串中的 32 个字符 + 空格后返回新行

标签 regex string powershell split

我希望在 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/

相关文章:

powershell - 尝试使用 PowerShell 脚本从 Active Directory 中的所有组中删除用户

asp.net - 如何使用 C# 在自定义验证器中包含正则表达式

php - 如何过滤波斯语字符的输入?

python - 正则表达式搜索显示不同的结果

JavaScript 正则表达式符号出现

java - 如何以每个用户都有一组属性的方式拆分点上的字符串?

javascript - 获取对象内部字符串中的最高数字

java - 在 String 中扩展环境变量

python - Powershell 与 Python sys.stdin.read() 的等价物是什么?

powershell - 为什么我收到警告 "The variable ' lastUpdate' is assigned but never used."在这个 PowerShell 中