【问题标题】:Returning new line after 32 characters + space in PowerShell strings在 PowerShell 字符串中的 32 个字符 + 空格后返回新行
【发布时间】:2021-02-26 03:31:20
【问题描述】:

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

您可能从上面的结果中可以看到,末尾的单词被截断,整个字符串没有被遍历或显示。如果有不同的策略或方法可以做到这一点,我们将不胜感激!

【问题讨论】:

  • 嗨,有什么对你有用的吗?如果您需要更多帮助,请通过评论告知。
  • 是的,它工作得很好,谢谢。
  • 我的声誉刚刚超过了我可以这样做的门槛,所以谢谢!
  • 成功了。不过,请参阅下面的最新帖子。由于其他原因,我正在尝试撤消替换。

标签: regex string powershell split


【解决方案1】:

使用“-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

【讨论】:

    【解决方案2】:

    你可以使用

    $Runonsentence = $Runonsentence -replace '(.{32}\S*)\s+', "`$1`r`n"
    

    请参阅regex demo

    或者,如果您更喜欢“向左走”并在零或最多 32 个以非空白字符结尾的字符后插入换行符,您可以使用

    $Runonsentence = $Runonsentence -replace '(.{0,31}\S)\s+', "`$1`r`n"
    

    this demo

    • (.{32}\S*) - 捕获组 1:除换行符之外的任何 32 个字符,然后是除空格之外的 0 个或多个字符
    • \s+ - 一个或多个空格字符。

    查看 PS 演示:



    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-16
      • 2014-04-17
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2015-07-05
      • 2020-11-14
      • 2017-06-09
      相关资源
      最近更新 更多