我正在尝试编写一个函数,对某些单词强制大写,如果后面跟有“s”,则在某些单词中添加“s”。例如,它应该使用grace s并将其转换为grace的
r"(\b)(grace)( (s|S))?\b": posessive_name,
{…}
def possessive_name(match: Match) -> str:
result = match.group(2).title()
result = result.replace(" ", "'")
return result # type: ignore
我正确地“标题化”了它,但不知道如何引用可选((s | s))组,以便在需要时添加('s),并且我希望避免添加额外的正则表达式。。。这可能吗
*为清晰起见,编辑名称
是的,像这样
您将获得:
您可以在组1中捕获1+个单词字符,然后使用character class匹配空格和s或s
在替换中,在组1上使用
.title()
并添加's
解释
(?<!\S)
左空白边界(\w+)
捕获组1,匹配1+单词字符[sS]
匹配一个空格,然后s
或S
(?!\S)
Regex demoPython demo
代码示例
输出
如果您想特别匹配grace,可以使用可选组。如果你想匹配更多的单词,你可以使用一个替代
(?:grace|anotherword)
Regex demo
示例代码
输出
相关问题 更多 >
编程相关推荐