Exscript.util.match module¶
Shorthands for regular expression matching.
-
Exscript.util.match.
any_match
(string, regex, flags=8)[source]¶ Matches the given string against the given regex.
- If no match is found, this function returns an empty list.
- If a match is found and the regular expression has no groups, a list of matching lines returned.
- If a match is found and the regular expression has one group, a list of matching strings is returned.
- If a match is found and the regular expression has multiple groups, a list containing tuples of matching strings is returned.
This behavior ensures that the following can never fail:
foo = '1 uno\n2 due' for m in any_match(foo, r'aaa'): # Returns [] print(m) for m in any_match(foo, r'\S+'): # Returns ['1 uno', '2 due'] print(m) for m in any_match(foo, r'(aaa)'): # Returns [] print(m) for m in any_match(foo, r'(\S+)'): # Returns ['1', '2'] print(m) for one, two in any_match(foo, r'(aaa) (\S+)'): # Returns [] print(m) for one, two in any_match(foo, r'(\S+) (\S+)'): # Returns [('1', 'uno'), ('2', 'due')] print(m)
Parameters: - string (string|Exscript.protocols.Protocol) – The string that is matched, or a Protocol object.
- regex (string) – A regular expression.
- flags (int) – The flags for compiling the regex; e.g. re.I
Return type: list[string|tuple]
Returns: A list of strings, or a list of tuples.
-
Exscript.util.match.
first_match
(string, regex, flags=8)[source]¶ Matches the given string against the given regex.
- If no match is found and the regular expression has zero or one groups, this function returns None.
- If no match is found and the regular expression has more than one group, this function returns a tuple of None. The number of elements in the tuple equals the number of groups in the regular expression.
- If a match is found and the regular expression has no groups, the entire string is returned.
- If a match is found and the regular expression has one group, the matching string from the group is returned.
- If a match is found and the regular expression has multiple groups, a tuple containing the matching strings from the groups is returned.
This behavior ensures that the following assignments can never fail:
foo = 'my test' match = first_match(foo, r'aaa') # Returns None match = first_match(foo, r'\S+') # Returns 'my test' match = first_match(foo, r'(aaa)') # Returns None match = first_match(foo, r'(\S+)') # Returns 'my' match = first_match(foo, r'(aaa) (\S+)') # Returns (None, None) match = first_match(foo, r'(\S+) (\S+)') # Returns ('my', 'foo')
Parameters: - string (string|Exscript.protocols.Protocol) – The string that is matched, or a Protocol object.
- regex (string) – A regular expression.
- flags (int) – The flags for compiling the regex; e.g. re.I
Return type: string|tuple
Returns: A match, or a tuple of matches.