Python 大于某个字符计数的正则表达式re.sub

Python 大于某个字符计数的正则表达式re.sub,python,regex,Python,Regex,我只需要在“example”超过一定数量的字符时替换东西。我想我应该可以用修饰语来做,但我似乎不知道怎么做 可以使用look aheads作为 example = re.sub('「[^)]*」','', example) (?=^.{5})先行断言。检查字符串是否包含5个(例如)字符 在这里,仅当字符串的最小长度为5个字符时,才会发生替换 或 概括的版本可以写成 example = re.sub('(?=^.{5})「[^)]*」','', example) 示例 length = "

我只需要在“example”超过一定数量的字符时替换东西。我想我应该可以用修饰语来做,但我似乎不知道怎么做

可以使用look aheads作为

example = re.sub('「[^)]*」','', example)
  • (?=^.{5})
    先行断言。检查字符串是否包含
    5个
    (例如)字符

    在这里,仅当字符串的最小长度为
    5
    个字符时,才会发生替换

概括的版本可以写成

example = re.sub('(?=^.{5})「[^)]*」','', example)
示例

length = "5"
re.sub('(?=^.{' + length +'})[^)]*','', example)

您可以将函数与
re.sub
一起使用。根据长度,您可以定义自己的函数并返回所需的内容。

一个示例以及预期的输出会更好。
>>> example = "hello"
>>> re.sub('(?=^.{3})[^)]*','', example)
''
>>> example = "hello"
>>> re.sub('(?=^.{10})[^)]*','', example)
'hello'
def repl(matchobj):
    if len(matchobj.group(0))>5:
        return #something



example = re.sub('「[^)]*」',repl, example)