【发布时间】:2018-11-02 16:42:56
【问题描述】:
我拥有的数据格式非常糟糕 .txt 。我试图捕捉这些开始和结束字符串之间的完整单词/句子。现在,我在一个文本中发现了大约 4 种类型的子字符串模式。我正在尝试捕获这些多个开始和结束子字符串之间的字符串。我能够正确捕获第一个字符串出现,但不能正确捕获第二个、第三个、...等。
开始和结束字符串: FOO,酒吧,酒吧,酒吧2
text = 'I do not want this FOO string1 BARS I do not want this FOO string 2 BAR I do not want this FOO string3 BAR2 I do not want this FOO string4 BARS '
snippet1 = text[text.index('FOO')+len('FOO'):text.index('BARS')] \
if text[text.index('FOO')+len('FOO'):text.index('BARS')] else ''
snippet2 = text[text.index('FOO')+len('FOO'):text.index('BAR')] \
if text[text.index('FOO')+len('FOO'):text.index('BAR')] else ''
snippet3 = text[text.index('FOO')+len('FOO'):text.index('BAR2')] \
if text[text.index('FOO')+len('FOO'):text.index('BAR2')] else ''
# print(type(snippet1))
print('')
print('snippet1:',snippet1) #Output: snippet1: string1
print('')
print('snippet2',snippet2) # Output: snippet2 string1
print('')
print('snippet3',snippet3) # Output: snippet3 string1 BARS I do not want this FOO string2 BAR I do not want this FOO string3
# How do I get this output? Is it possible to code this?
snippet1: string1
snippet2: string2
snippet3: string3
【问题讨论】:
标签: python regex string python-3.x