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

时间:2019-07-10 13:19:02

标签: python regex regex-group

我有以下字符串:

  

那只棕色的狐狸,那只猫(帽子),那只狗(磅)。帽子里的猫:

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

  

1)(帽子)中的猫

     

2)戴帽子的猫

我尝试了以下方法:

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)

1 个答案:

答案 0 :(得分:4)

严格匹配该字符串,您可以使用此正则表达式。为了概括起见,一开始的(?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)']