Powershell - 从字符串创建数组 - 用新行分隔文本块

发布于 2025-01-13 17:36:21 字数 525 浏览 0 评论 0原文

我的变量中有一个字符串:

$Test = @"
Paragraph 1: some paragraph text
some paragraph text some paragraph text
some paragraph text some paragraph text

Paragraph 2: some paragraph text
some paragraph text some paragraph text
some paragraph text some paragraph text

Paragraph 3: some paragraph text
some paragraph text some paragraph text
some paragraph text some paragraph text
"@

可能有未确定的段落数。

段落始终由换行符分隔。

我需要将每个段落文本块分隔成一个新的数组变量。

示例:

$Array[1] 应该给我第 2 段的整个文本块。

谢谢!

I have a string in a variable:

$Test = @"
Paragraph 1: some paragraph text
some paragraph text some paragraph text
some paragraph text some paragraph text

Paragraph 2: some paragraph text
some paragraph text some paragraph text
some paragraph text some paragraph text

Paragraph 3: some paragraph text
some paragraph text some paragraph text
some paragraph text some paragraph text
"@

There might be an undetermined number of paragraphs.

The paragraphs are always separated by a new line.

I need each paragraph block of text separated into a new array variable.

Example:

$Array[1] should give me the entire block of text of Paragraph 2.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

树深时见影 2025-01-20 17:36:21

由两个或多个连续换行符分割:

# Pipe to 
#  | ForEach-Object { "[$_]" } 
# to visualize the resulting array elements.
$test -split '(?:\r?\n){2,}'

有关传递到 -split 运算符及其实验能力,请参阅 此 regex101.com 页面

注意:

  • 如果您可以假设输入字符串中仅存在 Unix 格式的 LF (\n) 换行符,则可以将正则表达式简化为 '\n{2,} ' - 上面的正则表达式可以处理 LF 和 Windows CRLF (\r\n) 换行符。

  • 如果最后一段恰好包含您想要从数组中删除的单个尾随换行符(如果您使用 Get-Content -Raw 完整读取文本文件,通常会发生这种情况),使用:

    # 注意:如果您需要保留尾随 *非换行符* 空格,
    # 使用 .TrimEnd("`r", "`n") 代替。
    ($test -split '(?:\r?\n){2,}').TrimEnd()
    

Split by two or more consecutive newlines:

# Pipe to 
#  | ForEach-Object { "[$_]" } 
# to visualize the resulting array elements.
$test -split '(?:\r?\n){2,}'

For an explanation of the regex passed to the -split operator and the ability to experiment with it, see this regex101.com page.

Note:

  • If you can assume that only Unix-format LF (\n) newlines are present in your input string, you can simplify the regex to '\n{2,}' - the regex above handles both LF and Windows CRLF (\r\n) newlines.

  • If the last paragraph happens to contain a single trailing newline (as would typically happen if you read a text file in full with Get-Content -Raw) that you want to eliminate from the array, use:

    # Note: If you need to preserve trailing *non-newline* whitespace,
    #       use .TrimEnd("`r", "`n") instead.
    ($test -split '(?:\r?\n){2,}').TrimEnd()
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文