提取两个字符之间的单词,结束字符可以是两个不同的

问题描述 投票:0回答:1

我想在两个字符之间找到一个单词,但结束字符可以是两个不同的。 *) 或 |

我想要的文本是“特殊文本”(该文本行可以不同)

字符串可以如下所示: 大量文字(特殊文字|更多文字 但是也 很多文字(特殊文字

line = "a lot of text (*special text |more text*)"

substring = line[line.index('*')+1:line.index('|')]
print(substring)
python python-3.x
1个回答
1
投票

您应该使用

正则表达式
,而不是使用 index。例如,您可以搜索
(*
*)
之间的文本,然后将其拆分为
|
。请注意,
*
(
)
是正则表达式中的特殊字符,需要转义。

>>> import re
>>> line = "a lot of text (*special text |more text*) bla (*even more | special | text*)"
>>> re.findall(r"\(\*(.*?)\*\)", line)
['special text |more text', 'even more | special | text']
>>>: [y for x in re.findall(r"\(\*(.*?)\*\)", line) for y in x.split("|")]
['special text ', 'more text', 'even more ', ' special ', ' text']
© www.soinside.com 2019 - 2024. All rights reserved.