如何编写正则表达式来替换单词但在 Python 中保留其大小写? [英] How do I write a regex to replace a word but keep its case in Python?

查看:35
本文介绍了如何编写正则表达式来替换单词但在 Python 中保留其大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这甚至可能吗?

基本上,我想把这两个对 sub 的调用变成一个调用:

re.sub(r'\bAword\b', 'Bword', mystring)re.sub(r'\baword\b', 'bword', mystring)

我真正想要的是某种条件替换符号,例如:

re.sub(r'\b([Aa])word\b', '(?1=A:B,a:b)word')

我只关心第一个字符的大小写.其他都没有.

解决方案

您可以使用函数来解析每个匹配项:

<预><代码>>>>定义 f(匹配):返回 chr(ord(match.group(0)[0]) + 1) + match.group(0)[1:]>>>re.sub(r'\b[aA]word\b', f, 'aword Aword')'bword bword'

Is this even possible?

Basically, I want to turn these two calls to sub into a single call:

re.sub(r'\bAword\b', 'Bword', mystring)
re.sub(r'\baword\b', 'bword', mystring)

What I'd really like is some sort of conditional substitution notation like:

re.sub(r'\b([Aa])word\b', '(?1=A:B,a:b)word')

I only care about the capitalization of the first character. None of the others.

解决方案

You can have functions to parse every match:

>>> def f(match):
        return chr(ord(match.group(0)[0]) + 1) + match.group(0)[1:]

>>> re.sub(r'\b[aA]word\b', f, 'aword Aword')
'bword Bword'

这篇关于如何编写正则表达式来替换单词但在 Python 中保留其大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆