我有一系列这样的字符串:
*question: Question 1
*shuffle
Answer 1
Answer 2
*save: q1
*throwaway
>> q1_answer = "Answer 1"
*question: Question 2
*shuffle
Answer 1
Answer 2
Answer 3
*save: q2
*throwaway
>> q2_answer = "Answer 2"
我需要在*question
行和>>
行之间匹配文本,缩进整个文本块,并在其前面添加术语*group
例如:
*group
*question: Question 1
*shuffle
Answer 1
Answer 2
*save: q1
*throwaway
>> q1_answer = "Answer 1"
*group
*question: Question 2
*shuffle
Answer 1
Answer 2
Answer 3
*save: q2
*throwaway
>> q2_answer = "Answer 2"
我可以像这样匹配question
行:
rx = re.compile(r'(\*question.+)', re.M)
我可以像这样匹配>>
行:
rx2 = re.compile(r'(\>.+)', re.M)
但是我不确定如何在这两个定界符之间匹配所有内容并将其制表。
答案 0 :(得分:1)
使用re.sub()
。替换项可以是计算新字符串的函数,因此可以添加选项卡。
new_text = re.sub(r'\*question.+?>>',
lambda m: '*group\n\t' + m.group(0).replace('\n', '\n\t'),
text,
flags=re.DOTALL)