【问题标题】:python regex pattern that matches pattern including a repeated subgroup匹配包含重复子组的模式的python正则表达式模式
【发布时间】:2022-01-06 11:42:31
【问题描述】:

我正在寻找一种可以捕捉和替代的模式:

“随便什么1。[文档1]这是一个文档处理”

“随便什么 1.这是一个文件处理”

但当然只有在两个数字相同的情况下

一般:

“随便什么N。[文档N]这是一个正在处理的文档”

如果有帮助,N 必须在 1 到 1000 之间(即最多三个字符)

import re
mystr = "whatever whatever 1. [document 1] This is a document dealing with"
mystr = re.sub(r'([1-9]+)(\s)?(\.)(\s+)(\[Document )(*****)',r'\1\2\3\4',mystr)
                 ^^^^^^^^                            ^^^^^^

我必须在*****中提到第一组

我可以使用:

mystr = re.sub(r'([1-9]+)(\s)?(\.)(\s+)(\[Document )([1-9]+)',r'\1\2\3\4',mystr)

当然,这将包括以下情况: “随便什么 56. [文档 877] 这是一个处理文档”

我检查了一堆没有成功的答案: Regex: How to match a string that contains repeated pattern? Capture repeated groups in python regex Capturing repeating subpatterns in Python regex Regex with repeating groups python regular expression repeating group matches

【问题讨论】:

    标签: python regex regex-group


    【解决方案1】:

    您可以使用组和对数字的反向引用:

    由于我不确定您的全部条件是否匹配,因此我在此提供一个最小示例,假设唯一匹配的是一个最多 3 位数字的数字,后跟 [document {number}] 形式的引用:

    import re
    mystr = "whatever whatever 1. [document 1] This is a document dealing with"
    mystr = re.sub(r'((\d{1,3})\.)\s*\[document \2\]', r'\1', mystr)
    

    输出:'whatever whatever 1. This is a document dealing with'

    注意。在上面的示例中,要考虑的引用是 \2,如果您使用更多捕获组,则必须仔细更新此内容

    【讨论】:

    • 从数字1-999匹配\b(([1-9][0-9]{0,2})\.)\s+\[[Dd]ocument \2]
    • @Thefourthbird 谢谢,但我只是提供了一个最小的例子,重要的一点是 IMO 是反向引用 ;)(实际上我犹豫只是把\d+
    • 是的 ([1-9]\d{0,2}) 当然也可以
    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多