使用正则表达式解析带编号的分隔字符串

问题描述 投票:0回答:1

我正在使用PowerShell脚本解析文本文件。其中一些内容具有以下形式:

(1) first thing (2) other thing (that,has,details) (3) third thing: stuff (some details), first thing
(1) first thing (2) other thing (that,has,details) (3) third thing: stuff (some details), first thing (4) potentially (5) more (6) things (7) too

就像定界字符串一样,除了定界符是一个带括号的递增数字。我想将其解析为具有内容的字符串数组:

arr[0]="(1) first thing"
arr[1]="(2) other thing (that,has,details)"
arr[2]="(3) third thing: stuff (some details), first thing"

arr[0]="first thing"
arr[1]="other thing (that,has,details)"
arr[2]="third thing: stuff (some,details), first thing"

同时保持解决方案的灵活性以应对将来出现的其他问题。如果我可以将数字保留在单独的数组中,或者将数字和文本都保存在2D数组中,那将是令人难以置信的。

arr[0,0]="(1)"
arr[0,1]="first thing"
arr[1,0]="(2)"
arr[1,1]="other thing (that,has,details)"
arr[2,0]="(3)"
arr[2,1]="third thing: stuff (some,details), first thing"

我正在尝试使用正则表达式来执行此操作,但是遇到了一些麻烦。不愿意一起破解某些东西,因为使用正则表达式太好了。

谢谢您的帮助。

regex powershell parsing text-parsing delimited-text
1个回答
0
投票

完美的解决方案是

\K(\(\d+\))\s+((?:[^\(]|\((?!\d+\)))*[^\(\s])(?:\s+|$)

https://regex101.com/r/IhpQYD/1

...但是由于PowerShell使用.Net RegEx引擎,并且不支持\K,请使用

(\(\d+\))\s+((?:[^\(]|\((?!\d+\)))*[^\(\s])(?:\s+|$)

https://regex101.com/r/IhpQYD/2

© www.soinside.com 2019 - 2024. All rights reserved.