Skip to content

Commit

Permalink
[refactor] Use regex indices directly
Browse files Browse the repository at this point in the history
  • Loading branch information
Andy Chu committed Dec 15, 2023
1 parent 3af44f2 commit c5ffb67
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 13 deletions.
11 changes: 6 additions & 5 deletions builtin/func_eggex.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ def Call(self, rd):
# TODO: Support strings for named captures
i = rd.OptionalInt(default_=0)

groups = self.mem.RegexGroups()
num_groups = len(groups) # including group 0
s, indices = self.mem.GetRegexIndices()
num_groups = len(indices) / 2 # including group 0
if i < num_groups:
captured = groups[i]
if captured is None:
start = indices[2 * i]
end = indices[2 * i + 1]
if start == -1:
return value.Null
else:
return value.Str(captured)
return value.Str(s[start:end])
else:
if num_groups == 0:
msg = 'No regex capture groups'
Expand Down
10 changes: 6 additions & 4 deletions core/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1821,7 +1821,9 @@ def GetValue(self, name, which_scopes=scope_e.Shopt):
return value.List(items)

if name == 'BASH_REMATCH':
return value.BashArray(self.RegexGroups())
groups = util.RegexGroups(self.regex_string[-1],
self.regex_indices[-1])
return value.BashArray(groups)

# Do lookup of system globals before looking at user variables. Note: we
# could optimize this at compile-time like $?. That would break
Expand Down Expand Up @@ -2158,9 +2160,9 @@ def SetRegexIndices(self, s, indices):
self.regex_string[-1] = s
self.regex_indices[-1] = indices

def RegexGroups(self):
# type: () -> List[Optional[str]]
return util.RegexGroups(self.regex_string[-1], self.regex_indices[-1])
def GetRegexIndices(self):
# type: () -> Tuple[str, List[int]]
return self.regex_string[-1], self.regex_indices[-1]


#
Expand Down
7 changes: 3 additions & 4 deletions core/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@


def RegexGroups(s, indices):
# type: (str, Optional[List[int]]) -> List[str]
if indices is None:
return None

# type: (str, List[int]) -> List[str]
groups = [] # type: List[str]
n = len(indices)
for i in xrange(n / 2):
Expand All @@ -40,6 +37,8 @@ def simple_regex_search(pat, s):
# type: (str, str) -> List[str]
"""Convenience wrapper around libc."""
indices = libc.regex_search(pat, 0, s)
if indices is None:
return None
return RegexGroups(s, indices)


Expand Down

0 comments on commit c5ffb67

Please sign in to comment.