Powershell - 从字符串创建数组 - 用新行分隔文本块
我的变量中有一个字符串:
$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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由两个或多个连续换行符分割:
有关传递到
-split
运算符及其实验能力,请参阅 此 regex101.com 页面。注意:
如果您可以假设输入字符串中仅存在 Unix 格式的 LF (
\n
) 换行符,则可以将正则表达式简化为'\n{2,} '
- 上面的正则表达式可以处理 LF 和 Windows CRLF (\r\n
) 换行符。如果最后一段恰好包含您想要从数组中删除的单个尾随换行符(如果您使用
Get-Content -Raw
完整读取文本文件,通常会发生这种情况),使用:Split by two or more consecutive newlines:
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: