gpt4 book ai didi

python - 当第一个子字符串后有空格时,在 Python 中查找两个子字符串之间的字符串

转载 作者:太空狗 更新时间:2023-10-30 02:15:33 30 4
gpt4 key购买 nike

虽然 StackOverflow 上有几篇帖子与此类似,但没有一篇涉及目标字符串是其中一个子字符串后一个空格的情况。

我有以下字符串(example_string): <insert_randomletters>[?] I want this string.Reduced<insert_randomletters>

我想提取“我想要这个字符串”。从上面的字符串。随机字母将始终更改,但是引用“我想要这个字符串”。永远在 [?] 之间(在最后一个方括号后有一个空格)和 Reduced。

现在,我可以执行以下操作来提取“我想要这个字符串”。

target_quote_object = re.search('[?](.*?)Reduced', example_string)
target_quote_text = target_quote_object.group(1)
print(target_quote_text[2:])

这消除了 ]总是出现在我提取的字符串的开头,因此只打印“我想要这个字符串”。然而,这个解决方案看起来很难看,我宁愿做 re.search()返回当前目标字符串而不做任何修改。我该怎么做?

最佳答案

您的 '[?](.*?)Reduced' 模式匹配文字 ?,然后捕获除换行符以外的任何 0+ 个字符,少至可能到第一个 Reduced 子串。 [?] 是一个字符类,由未转义的括号组成,而字符类中的 ? 是文字 ?字符。这就是为什么您的第 1 组包含 ] 和一个空格。

要使您的正则表达式匹配 [?],您需要转义 [?,它们将作为文字字符进行匹配。此外,您需要在 ] 之后添加一个空格,以确保它不会落入第 1 组。更好的主意是使用 \s* (0 个或更多空格) 或 \s+(出现 1 次或多次)。

使用

re.search(r'\[\?]\s*(.*?)Reduced', example_string)

参见 regex demo .

import re
rx = r"\[\?]\s*(.*?)Reduced"
s = "<insert_randomletters>[?] I want this string.Reduced<insert_randomletters>"
m = re.search(r'\[\?]\s*(.*?)Reduced', s)
if m:
print(m.group(1))
# => I want this string.

参见 Python demo .

关于python - 当第一个子字符串后有空格时,在 Python 中查找两个子字符串之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49591343/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com