如何使用 python 从包含括号的字符串中提取子字符串?
How would I extract a substring from a string that contains parentheses using python?
我有以下字符串:
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)
严格匹配那个字符串,你可以使用这个正则表达式。为了将来概括,开头的 (?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)']
我有以下字符串:
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)
严格匹配那个字符串,你可以使用这个正则表达式。为了将来概括,开头的 (?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)']