1
1
from .regex_tree import Alternative , BackReference , CharClasses , RegexTree
2
2
3
+
3
4
class RegexError (Exception ):
4
5
def __init__ (self , regex : str , index : int , message : str ):
5
6
self .regex = regex
@@ -8,7 +9,7 @@ def __init__(self, regex: str, index: int, message: str):
8
9
9
10
def __str__ (self ):
10
11
caret_line = ' ' * self .index + '^'
11
- return f"{ self .regex } \n { caret_line } \n { self .message } "
12
+ return f"\n { self .regex } \n { caret_line } \n { self .message } "
12
13
13
14
14
15
class RegexParser :
@@ -36,25 +37,32 @@ def _parseRegex(self, to_close: bool) -> RegexTree:
36
37
self .index += 1
37
38
match char :
38
39
case '(' :
39
- name = None
40
40
if self .index < len (self .regex ) and self .regex [self .index ] == '?' :
41
41
self .index += 1
42
- if self .index >= len (self .regex ) or self . regex [ self . index ] != '<' :
42
+ if self .index >= len (self .regex ):
43
43
self ._raise_error ("Invalid named group" )
44
- self .index += 1
45
- name = ''
46
- while self .index < len (self .regex ) and self .regex [self .index ] != '>' :
47
- name += self .regex [self .index ]
44
+ elif self .regex [self .index ] == '<' :
48
45
self .index += 1
49
- if self .index >= len (self .regex ) or self .regex [self .index ] != '>' or name == '' :
50
- self ._raise_error ("Invalid named group" )
51
- self .index += 1
52
- if name in named_groups :
53
- self ._raise_error ("Duplicate named group" )
54
- subTree = self ._parseRegex (True )
55
- if name is not None :
56
- named_groups [name ] = subTree
57
- ordered_groups .append (subTree )
46
+ name = ''
47
+ while self .index < len (self .regex ) and self .regex [self .index ] != '>' :
48
+ name += self .regex [self .index ]
49
+ self .index += 1
50
+ if self .index >= len (self .regex ) or self .regex [self .index ] != '>' or name == '' :
51
+ self ._raise_error ("Invalid named group" )
52
+ self .index += 1
53
+ if name in named_groups :
54
+ self ._raise_error ("Duplicate named group" )
55
+ subTree = self ._parseRegex (True )
56
+ named_groups [name ] = subTree
57
+ ordered_groups .append (subTree )
58
+ elif self .regex [self .index ] == ':' :
59
+ self .index += 1
60
+ subTree = self ._parseRegex (True )
61
+ else :
62
+ self ._raise_error ("Invalid group" )
63
+ else :
64
+ subTree = self ._parseRegex (True )
65
+ ordered_groups .append (subTree )
58
66
elements .append (subTree )
59
67
case ')' :
60
68
if not to_close :
0 commit comments