美文网首页
import regex as re

import regex as re

作者: sacredrelic | 来源:发表于2018-06-16 11:23 被阅读0次

    regex 是一个向后兼容 re 的功能更强大的 Python 正则库
    支持重复的 group names, 从此不再为 error: redefinition of group name … 所困扰

    >>> # With optional groups:
    >>>
    >>> # Both groups capture, the second capture 'overwriting' the first.
    >>> m = regex.match(r"(?P<item>\w+)? or (?P<item>\w+)?", "first or second")
    >>> m.group("item")
    'second'
    >>> m.captures("item")
    ['first', 'second']
    >>> # Only the second group captures.
    >>> m = regex.match(r"(?P<item>\w+)? or (?P<item>\w+)?", " or second")
    >>> m.group("item")
    'second'
    >>> m.captures("item")
    ['second']
    >>> # Only the first group captures.
    >>> m = regex.match(r"(?P<item>\w+)? or (?P<item>\w+)?", "first or ")
    >>> m.group("item")
    'first'
    >>> m.captures("item")
    ['first']
    >>>
    >>> # With mandatory groups:
    >>>
    >>> # Both groups capture, the second capture 'overwriting' the first.
    >>> m = regex.match(r"(?P<item>\w*) or (?P<item>\w*)?", "first or second")
    >>> m.group("item")
    'second'
    >>> m.captures("item")
    ['first', 'second']
    >>> # Again, both groups capture, the second capture 'overwriting' the first.
    >>> m = regex.match(r"(?P<item>\w*) or (?P<item>\w*)", " or second")
    >>> m.group("item")
    'second'
    >>> m.captures("item")
    ['', 'second']
    >>> # And yet again, both groups capture, the second capture 'overwriting' the first.
    >>> m = regex.match(r"(?P<item>\w*) or (?P<item>\w*)", "first or ")
    >>> m.group("item")
    ''
    >>> m.captures("item")
    ['first', '']
    

    此外,regex 还支持模糊匹配等操作
    更多功能,移步 pypi

    相关文章

      网友评论

          本文标题:import regex as re

          本文链接:https://www.haomeiwen.com/subject/cqxbeftx.html