为什么我要通过一个可调用的re.sub公司字符串要大写吗?

2024-05-20 01:52:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个有点做作的例子,在我最后的问题。。。在

我想用regex来大写所有格名词的第一个字符。假设我有一个正则表达式(可能很难)匹配所有格名词。也就是说。。。在

### Regex explanation ###
# 1. match a word break
# 2. match a word-like character and capture in a group
# 3. lookahead for some more characters + the substring "'s"

>>> my_re = re.compile(r"\b(\w)(?=\w+'s)")
>>> re.search(my_re, "bruce's computer")
<_sre.SRE_Match object; span=(0, 1), match='b'>

>>> re.search(my_re, "bruce's computer").group(1)
'b'

在本例中,它按预期工作。所以,我认为所有要做的就是打电话给sub的第一组,它应该可以工作,对吗?在

^{pr2}$

这并不是预期的,也不是显而易见的,为什么它不是资本。经过一番研究,我在re.sub公司文档。。。在

Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.

事实上,通过一个callable确实有用。。。在

>>> re.sub(my_re, lambda x: x.group(1).upper(), "bruce's computer")
"Bruce's computer"

太好了。我想了解的是为什么这样做,否则如果不查找,我就不记得如何正确地为这种类型的实例使用API了。任何方向都将不胜感激。在


Tags: andtheinrestringmymatchgroup
1条回答
网友
1楼 · 发布于 2024-05-20 01:52:24

第二个参数可以是string或callable。在

re.sub(my_re, r'\1'.upper(), "bruce's computer"):将一个\1string传递给sub函数(上面或不是上面的,不重要)

re.sub(my_re, lambda x: x.group(1).upper(), "bruce's computer"):传递的是一个可调用的,因此^{有效,因为它应用于结果。在

不会立即计算x.group(1).upper(),因为它包含在lambda表达式中,相当于非lambda:

def func(x):
   return x.group(1).upper()

也可以传递给re.subre.sub(my_re, func, "bruce's computer"),注意在这种情况下缺少()!在

相关问题 更多 >