gpt4 book ai didi

python - 如何使用 python 从包含括号的字符串中提取子字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:35 24 4
gpt4 key购买 nike

我有以下字符串:

The quick brown fox, the cat in the (hat) and the dog in the pound. The Cat in THE (hat):

我需要帮助来提取以下文本:

1) the cat in the (hat)

2) The Cat in THE (hat)

我尝试了以下方法:

p1 = """The quick brown fox, the cat in the (hat) and the dog in the pound. The Cat in THE (hat)"""
pattern = r'\b{var}\b'.format(var = p1)
with io.open(os.path.join(directory,file), 'r', encoding='utf-8') as textfile:
for line in textfile:
result = re.findall(pattern, line)
print (result)

最佳答案

严格匹配那个字符串,你可以使用这个正则表达式。为了对 future 进行概括,开头的 (?i) 使其忽略大小写并使用 \ 来转义括号。

import re
regex = re.compile('(?i)the cat in the \(hat\)')
string = 'The quick brown fox, the cat in the (hat) and the dog in the pound. The Cat in THE (hat):'
regex.findall(string)

结果:

['the cat in the (hat)', 'The Cat in THE (hat)']

关于python - 如何使用 python 从包含括号的字符串中提取子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56971633/

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