本文介绍了Python - 修改反向引用.可以做到吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 新手,请原谅我的无知.我正在尝试修改正则表达式中的反向引用字符串.

New to Python so please forgive my ignorance. I'm trying to modify backreferenced strings in a regular expression.

示例:

>>>a_string
'fsa fad fdsa dsafasdf u.s.a. U.S.A. u.s.a fdas adfs.f fdsa f.afda'
>>> re.sub(r'(?<=\s)(([a-zA-Z]\.)+[a-zA-Z]\.{0,1})(?=\s)', '<acronym>'+re.sub(r'\.',r'',(r'\1').upper())+'</acronym>', a_string)
'fsa fad fdsa dsafasdf <acronym>u.s.a.</acronym> <acronym>U.S.A.</acronym> <acronym>u.s.a</acronym> fdas adfs.f fdsa f.afda'

而不是我想要的输出:

'fsa fad fdsa dsafasdf <acronym>USA</acronym> <acronym>USA</acronym> <acronym>USA</acronym> fdas adfs.f fdsa f.afda'

感谢您的帮助.

推荐答案

来自 文档:

如果 repl 是一个函数,它会在 pattern 的每个非重叠出现时被调用.该函数采用单个匹配对象参数,并返回替换字符串.例如:

并查看链接文档中包含的示例.

And see the example contained in the linked docs.

这篇关于Python - 修改反向引用.可以做到吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 06:13