ure – 正则表达式

该模块实现相应CPython模块的子集,如下所示。更多信息,请参见 |CPython文档| python:re.

该模块实现正则表达式操作。支持的正则表达式语法是CPython re 模块的一个子集(实际上是POSIX扩展正则表达式的子集)。

支持运营商为:

'.'
匹配任何字符。
'[]'
匹配字符集。支持单个字符和范围。
'^'
Match the start of the string.
'$'
Match the end of the string.
'?'
Match zero or one of the previous entity.
'*'
Match zero or more of the previous entity.
'+'
Match one or more of the previous entity.

'??'

'*?'

'+?'

'|'
Match either the LHS or the RHS of this operator.
'(...)'
Grouping. Each group is capturing (a substring it captures can be accessed with match.group() method).

不支持计数重复({m,n})、更高级断言、名称组等。

函数

ure.compile(regex_str)

编译正则表达式,返回 正则表达式对象 对象。

ure.match(regex_str, string)

正则表达式对象string 匹配。匹配通常从字符串的起始位置进行。

ure.search(regex_str, string)

string 中搜索 正则表达式对象 。与 match 不同,这将首先搜索与正则表达式相匹配的字符串(若正则表达式固定,则字符串为0)。

ure.sub(regex_str, replace, string, count=0, flags=0)

Compile regex_str and search for it in string, replacing all matches with replace, and returning the new string.

replace can be a string or a function. If it is a string then escape sequences of the form \<number> and \g<number> can be used to expand to the corresponding group (or an empty string for unmatched groups). If replace is a function then it must take a single argument (the match) and should return a replacement string.

If count is specified and non-zero then substitution will stop after this many substitutions are made. The flags argument is ignored.

Note: availability of this function depends on MicroPython port.

ure.DEBUG

标记值,显示有关已编译表达式的调试信息。

正则表达式对象

编译正则表达式。该类实例使用 ure.compile() 创建。

regex.match(string)
regex.search(string)
regex.sub(replace, string, count=0, flags=0)

与模块级函数 match()search() , sub 相似。若将同一正则表达式应用于多个字符串,则使用该方法会大大提高效率。

regex.split(string, max_split=-1)

使用正则表达式拆分字符串。若给定,则指定将拆分的最大数量。返回字符串列表(若指定,则可能会有多达 max_split+1 个元素)。

Match 对象

匹配由 match()search() 方法返回的对象。And passed to the replacement function in sub().

match.group([index])

Return matching (sub)string. index is 0 for entire match, 1 and above for each capturing group. 返回匹配(子)字符串。若完全匹配 index 为0, 对于每个捕获组为1或更多。 仅支持数字组。

match.groups()

Return a tuple containing all the substrings of the groups of the match.

Note: availability of this method depends on MicroPython port.

match.start([index])
match.end([index])

Return the index in the original string of the start or end of the substring group that was matched. index defaults to the entire group, otherwise it will select a group.

Note: availability of these methods depends on MicroPython port.

match.span([index])

Returns the 2-tuple (match.start(index), match.end(index)).

Note: availability of this method depends on MicroPython port.