Bru*_*cci 4 python regex string
下面是一个有点人为的例子,它解决了我最终的问题......
我想使用正则表达式将所有格名词的第一个字符大写。假设我有一个正则表达式(可能很差)匹配所有格名词。IE...
### 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'
Run Code Online (Sandbox Code Playgroud)
对于此示例,它按预期工作。所以,我认为所有要做的就是在 sub 中的第一组上调用 upper 并且它应该可以工作,对吧?
>>> re.sub(my_re, r'\1'.upper(), "bruce's computer")
"bruce's computer"
Run Code Online (Sandbox Code Playgroud)
这不是预期的或显而易见的为什么它不是资本。经过一番研究,我在 re.sub 文档中发现了这一点...
返回通过替换 repl 替换 string 中模式的最左侧非重叠出现而获得的字符串。repl 可以是字符串或可调用的;如果是字符串,则处理其中的反斜杠转义。如果它是可调用的,则传递匹配对象并且必须返回要使用的替换字符串。
确实传递一个可调用的确实有效......
>>> re.sub(my_re, lambda x: x.group(1).upper(), "bruce's computer")
"Bruce's computer"
Run Code Online (Sandbox Code Playgroud)
伟大的。我想了解的是为什么这行得通,否则我将不记得如何在不查找的情况下为此类实例正确使用 API。任何方向将不胜感激。
第二个参数可以是字符串或可调用的。
re.sub(my_re, r'\1'.upper(), "bruce's computer"):您正在向函数传递一个\1 字符串sub(上与否,无关紧要)
re.sub(my_re, lambda x: x.group(1).upper(), "bruce's computer"):您正在传递一个callable,因此upper()有效,因为它适用于结果。
x.group(1).upper() 不会立即计算,因为它包含在 lambda 表达式中,相当于非 lambda:
def func(x):
return x.group(1).upper()
Run Code Online (Sandbox Code Playgroud)
您也可以传递给re.sub: re.sub(my_re, func, "bruce's computer"),请注意()在这种情况下缺少!