假设文字
text =“”“ {| p {3cm} | p {3cm} | p {3cm} |} \ hline \ multi {3} {| c |} {城市列表} \ \ hline名称...”“ “
我只想将第一个花括号的内容作为子集。因此,所需的输出为:
desired_output =“ p {3cm} | p {3cm} | p {3cm}”
当前,我收到了行中所有卷曲小节的内容
text = """{ |p{3cm}|p{3cm}|p{3cm}| } \\hline \\multi{3}{|c|}{City List} \\ \\hline Name ... """
import re
false_output = re.findall(r'\{(.*?)\}',text)
false_output
#[' |p{3cm', '3cm', '3cm', '3', '|c|', 'City List']
#also no success with:
re.findall(r'({\w+\})',a)
我不认为可以使用正则表达式来完成。上一次我不得不解决这样的问题(解析Wikitext)时,我最终使用了堆栈,每当我有开场符时就增加,在遇到结束符时减少,在找到最后一个字符时退出。
请注意,这对于重复的第一级括号是无效的。
该代码比这更优化,但是基本思想如下:
def keep_between(text, start, end):
counter = 0
result = []
beginning = text.find(start)
if beginning != -1:
remaining_text = text[beginning:]
for c in remaining_text:
if c == start:
counter += 1
continue
if c == end:
counter -= 1
continue
if not counter:
break
result.append(c)
return ''.join(result)
print(keep_between(text, '{', '}'))
让我' |p3cm|p3cm|p3cm| '