Search code examples
regexpowershellpowershell-4.0

Get content with RegEx between braces and a keyword


I'm just facing with a problem, what I cannot solve it. I tried to build up my regex pattern which has to be get the content between braces but if only an exact keyword is stands before the open brace.

(?<=(?:\testlist\b)|(?:){)((.*?)(?=}))

The whole content itself may contains many blocks (which are always beginning with a keyword), like:

nodelist{
...
...
}
testlist
{
...
...
}

With the above pattern I can get each of node contents but I would like to specify in regex that only 'testlist' node's content has to be grabbed. (Position of braces are different by design because I would like to get the content even if the braces are in the same line as the keyword or no matter, how many line breaks contains after it)

Does anyone any idea, how can I achieve this?

Thank you!


Solution

  • You can use a regex like

    (?s)testlist\s*{(.*?)}
    

    This matches testlist literally, followed by spaces and a literal opening brace. (.*?) captures everything until the next closing brace.

    Usage:

    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>   
    

    If you want a full match instead of a capture group:

    PS C:\Users\greg> 'nodelist{
    >> ...
    >> ...
    >> }
    >> testlist
    >> {
    >> ...
    >> ...
    >> }' -match '(?s)(?<=testlist\s*{).*?(?=})'
    True
    PS C:\Users\greg> $Matches.0
    
    ...
    ...
    
    PS C:\Users\greg>