get inner patterns recursively using regex c#

前端 未结 1 1347
余生分开走
余生分开走 2020-12-10 06:56

i know there are several questions about regex recursion in .net. I can write somewhat complex regex expressions but this recursion is beyond me, i am just not able to write

相关标签:
1条回答
  • 2020-12-10 07:37

    Here's a pattern that might satisfy your needs:

    ^\[!((?<n>\w+='\[!)|(?<inner-n>!]')|\w+='(?!\[!)[^']*'| )*!](?!(n))$
    

    It will give the innermost item for each item in order. To explain what I mean, given the code:

    [!a='test' c='[!x='blah'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]' !]
    

    It will give the following matches (in the capture collection for the group "inner"):

    x='blag'
    y='innermost'
    a='[!y='innermost'!]' b='innervalue'
    

    So, for each x=y item in the [! .. !], it will give the matches in order from innermost outwards.

    If you also want the overall expression to be captured you can modify it like this:

    ^(?<n>\[!)((?<n>\w+='\[!)|(?<inner-n>!]')|\w+='(?!\[!)[^']*'| )*(?<inner-n>!])(?!(n))$
    

    Giving:

    x='blag'
    y='innermost'
    a='[!y='innermost'!]' b='innervalue'
    a='test' c='[!x='blag'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]' 
    

    And to explain the regex:

    ^       # start of string
    \[!     # start of overall [! .. !]
    (       # either ...
        (?<n>\w+='\[!)|     # a complex x='[! .. !]' containing a nested [! .. !] - push this onto the stack 'n'
        (?<inner-n>!]')|    # end of a nested [! .. !] - pop stack 'n', and capture the contents into 'inner'
        \w+='(?!\[!)[^']*'| # a simple x='asdf' with no nested [! .. !]
         )                  # or a space
    *       # as many times as you want
    !]      # the end of the overall [! .. !]
    (?!(n)) # assert that the 'n' stack is empty, no mismatched [! .. !]
    $       # end of string
    
    0 讨论(0)
提交回复
热议问题