在Python正则表达式中处理可选组的最佳方法是什么?

2024-10-05 21:54:58 发布

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

我正在尝试编写一个函数,对某些单词强制大写,如果后面跟有“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),并且我希望避免添加额外的正则表达式。。。这可能吗

*为清晰起见,编辑名称


Tags: 函数nametitledefmatchgroupresult单词
3条回答

是的,像这样

import re

test_str = "This is grace s apple."

def fix_names(match):
    name, s = match.groups()
    name = name.title()
    if s:
        name = f"{name}'s"
    return name

p = re.compile(r"\b(grace)(\s[sS])?\b")
print(p.sub(fix_names, test_str))
lines = (
    'a grace s apple',
    'the apple is grace s',
    'take alice s and steve s',
)
for line in lines:
    result = re.sub(r'(\w+)\s+s($|\s)', lambda m: m.group(1).title()+"'s"+m.group(2), line, flags=re.I|re.S)
    print(result)

您将获得:

a Grace's apple

the apple is Grace's

take Alice's and Steve's

您可以在组1中捕获1+个单词字符,然后使用character class匹配空格和s或s

在替换中,在组1上使用.title()并添加's

(?<!\S)(\w+) [sS](?!\S)

解释

  • (?<!\S)左空白边界
  • (\w+)捕获组1,匹配1+单词字符
  • [sS]匹配一个空格,然后sS
  • (?!\S)

Regex demoPython demo

代码示例

import re
test_str = "grace s"
regex = r"(?<!\S)(\w+) [sS](?!\S)"
result = re.sub(regex, lambda match: match.group(1).title()+"'s", test_str)
print(result)

输出

Grace's

如果您想特别匹配grace,可以使用可选组。如果你想匹配更多的单词,你可以使用一个替代(?:grace|anotherword)

(?<!\S)(grace)(?: ([sS]))?\b

Regex demo

示例代码

import re
test_str = "Her name is grace."
strings = [
    "grace s",
    "Her name is grace."
]
pattern = r"(?<!\S)(grace)(?: ([sS]))?\b"
regex = re.compile(pattern)

for s in strings:
    print(
        regex.sub(
            lambda m: "{}{}".format(m.group(1).title(), "'s" if m.group(2) else '')
            , s)
    )

输出

Grace's
Her name is Grace.

相关问题 更多 >