加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何返回匹配某些文本的正则表达式?

发布时间:2020-12-14 02:30:22 所属栏目:百科 来源:网络整理
导读:Javascript正则表达式问题 Return the part of the regex that matched的答案是“不,因为编译破坏了正则表达式文本和匹配逻辑之间的关系.” 但Python保留了Match Objects,re.groups()返回触发匹配的特定组.将每个组的正则表达式文本保留为匹配对象的一部分并
Javascript正则表达式问题 Return the part of the regex that matched的答案是“不,因为编译破坏了正则表达式文本和匹配逻辑之间的关系.”

但Python保留了Match Objects,re.groups()返回触发匹配的特定组.将每个组的正则表达式文本保留为匹配对象的一部分并返回它应该很简单,但似乎没有这样做的调用.

import re

pat = "(^d+$)|(^w+$)|(^W+$)"
test = ['a','c3','36d','51','29.5','#$%&']
for t in test:
    m = re.search(pat,t)
    s = (m.lastindex,m.groups()) if m else ''
    print(str(bool(m)),s)

返回:

True (2,(None,'a',None))
True (2,None))
True (1,('51',None,None))
False
True (3,'#$%&'))

编译器显然知道这种模式中有三个组.有没有办法在正则表达式中提取每个组中的子模式,例如:

>>> print(m.regex_group_text)

('^d+$','^w+$','^W+$')

是的,可以编写自定义模式解析器,例如拆分“|”对于这种特殊的模式.但是,使用re编译器对每个组中文本的理解会更容易,更可靠.

如果索引不够并且您绝对需要知道正则表达式的确切部分,则可能没有其他可能性,只能自己解析表达式的组.

总而言之,这没什么大不了的,因为您只需计算开始和结束括号并记录其索引:

def locateBraces(inp):
    bracePositions = []
    braceStack = []
    depth = 0
    for i in range(len(inp)):
        if inp[i] == '(':
            braceStack.append(i)
            depth += 1
        if inp[i] == ')':
            bracePositions.append((braceStack.pop(),i))
            depth -= 1
            if depth < 0:
                raise SyntaxError('Too many closing braces.')
    if depth != 0:
        raise SyntaxError('Too many opening braces.')
    return bracePositions

Edited: This dumb implementation only counts opening and closing braces. However,regexes may contain escaped braces,e.g. (,which are
counted as regular group-defining braces using this method. You may
want to adapt it to omit braces that have an uneven number of
backslashes right before them. I leave this issue as a task for you

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读