From e1e5b39fde51b4779164c750693c8ee437d1b440 Mon Sep 17 00:00:00 2001 From: OverloadedTech Date: Tue, 17 Nov 2026 10:35:39 +0100 Subject: [PATCH] fix: allow an escaped backslash at the end of a Value regex The check for an escaped closing ')' only looked at the character before it, so a regex ending in an escaped backslash like ([A-Z]:\\) was rejected as not being inside a '()' pair. Count the backslashes instead and only reject an odd number. --- tests/textfsm_test.py | 9 +++++++++ textfsm/parser.py | 4 +++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/textfsm_test.py b/tests/textfsm_test.py index c3d2386..5eb202b 100755 --- a/tests/textfsm_test.py +++ b/tests/textfsm_test.py @@ -76,6 +76,15 @@ def testFSMValue(self): textfsm.TextFSMTemplateError, v.Parse, r'Value beer (boo)hoo\)' ) + # An escaped backslash before the closing parenthesis is allowed. + v = textfsm.TextFSMValue(options_class=textfsm.TextFSMOptions) + v.Parse(r'Value beer (boo\\)') + self.assertEqual(v.regex, r'(boo\\)') + self.assertEqual(v.template, r'(?Pboo\\)') + self.assertRaises( + textfsm.TextFSMTemplateError, v.Parse, r'Value beer (boo)hoo\\\)' + ) + # A missing regex is a template error, not an IndexError. v = textfsm.TextFSMValue(options_class=textfsm.TextFSMOptions) self.assertRaises( diff --git a/textfsm/parser.py b/textfsm/parser.py index 4c691be..1192f50 100755 --- a/textfsm/parser.py +++ b/textfsm/parser.py @@ -305,11 +305,13 @@ def Parse(self, value): "Invalid Value name '%s' or name too long." % self.name ) + # An odd number of backslashes before the final ')' means it is escaped. + backslashes = len(self.regex[:-1]) - len(self.regex[:-1].rstrip('\\')) if ( not self.regex or self.regex[0] != '(' or self.regex[-1] != ')' - or self.regex[-2] == '\\' + or backslashes % 2 ): raise TextFSMTemplateError( "Value '%s' must be contained within a '()' pair." % self.regex