我只是面临一个问题,我无法解决它。 我尝试构建我的正则表达式模式,该模式必须获取大括号之间的内容,但如果只有一个确切的关键字位于左大括号之前。
(?<=(?:\testlist\b)|(?:){)((.*?)(?=}))
整个内容本身可能包含许多 block (总是以关键字开头),例如:
nodelist{
...
...
}
testlist
{
...
...
}
通过上述模式,我可以获取每个节点内容,但我想在正则表达式中指定只有“teSTList”节点的内容必须被抓取。 (大括号的位置在设计上是不同的,因为我想获取内容,即使大括号与关键字在同一行,或者不管它后面包含多少换行符)
有谁知道,我怎样才能实现这个目标?
谢谢!
最佳答案
您可以使用正则表达式,例如
(?s)testlist\s*{(.*?)}
这与 teSTList
字面匹配,后跟空格和字面左大括号。 (.*?)
捕获所有内容,直到下一个右大括号。
用法:
PS C:\Users\greg> 'nodelist{
>> ...
>> ...
>> }
>> testlist
>> {
>> ...
>> ...
>> }' -match '(?s)testlist\s*{(.*?)}'
True
PS C:\Users\greg> $Matches.0
testlist
{
...
...
}
PS C:\Users\greg> $Matches.1
...
...
PS C:\Users\greg>
如果您想要完整匹配而不是捕获组:
PS C:\Users\greg> 'nodelist{
>> ...
>> ...
>> }
>> testlist
>> {
>> ...
>> ...
>> }' -match '(?s)(?<=testlist\s*{).*?(?=})'
True
PS C:\Users\greg> $Matches.0
...
...
PS C:\Users\greg>
关于regex - 使用大括号和关键字之间的 RegEx 获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60290430/