dmulyalin / ttp

Template Text Parser
MIT License
350 stars 34 forks source link

Feature request: match a string that is collected by previous match #61

Closed pdimop closed 3 years ago

pdimop commented 3 years ago

I am trying to create a template for "show run" for cisco IOS XR and trying to collect the banner. The format is:

banner motd &
BANNER MESSAGE
BANNER MESSAGE
&

where & is an arbitrary text. I ask for a feature to match the above code with a template such as:

banner {{ bannertype }} {{ end-of-banner-marker }}
{{ banner-text | _line_ | joinmatches }}
$end-of-banner-marker${{ _end_ }}
dmulyalin commented 3 years ago

Hi,

Thank you for raising this feature request, but its too hard to implement, will require lots of changes in the code base and use case is no the very common by the look of it, meaning it does not worth the efforts at least at this stage.

Suggest this workaround instead:

data = """
banner motd &
BANNER MESSAGE line 1
BANNER MESSAGE line 2
BANNER MESSAGE line 3
&
some
other staff
"""

template_to_match_marker = "banner motd {{ marker }}"

template_to_parse_banner = """
<group name="motd">
banner motd {{ ignore(banner_marker) }} {{ _start_ }}
{{ banner_mesage | _line_ | joinmatches("\\n") }}
{{ ignore(banner_marker) }} {{ _end_ }}
</group>
"""

# extract marker value
parser = ttp(data, template_to_match_marker)
parser.parse()
marker = parser.result()[0][0]["marker"]

# parse banner
parser = ttp(data, template_to_parse_banner, vars={"banner_marker": marker})    
parser.parse()
res = parser.result()
import pprint; pprint.pprint(res)
# prints:
# [[{'motd': {'banner_mesage': 'BANNER MESSAGE line 1\n'
#                              'BANNER MESSAGE line 2\n'
#                              'BANNER MESSAGE line 3'}}]]

Hope that helps.

pdimop commented 3 years ago

Thank you very much