python - 匹配包含特定文本的整行,并在换行符后添加字符串

标签 python regex

假设我有一个像这样的字符串:

*question: What percentage is the correct answer? 
    33%
    15%
    2%
    25%

我需要在问题行之后添加一个shuffle命令:

*question: What percentage is the correct answer? 
    *shuffle
    33%
    15%
    2%
    25%

这样做的最佳方法是什么?我可以使用任何记事本编辑器或 Python。

我想我可以使用以下正则表达式来捕获第一行的所有内容:^(\*question).*,但我不确定如何添加 *shuffle 语法直接位于换行符之后。

最佳答案

您可以使用

import re

data = """
*question: What percentage is the correct answer? 
    33%
    15%
    2%
    25%
"""

rx = re.compile(r'(\*question.+)', re.M)

data = rx.sub(r'\1\n    *shuffle', data)
print(data)

哪个产量

*question: What percentage is the correct answer? 
    *shuffle
    33%
    15%
    2%
    25%

关于python - 匹配包含特定文本的整行,并在换行符后添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631737/

相关文章:

python - 在Python中,如何模拟c扩展类?

python - 多源服务器简单开发http-proxy

javascript - 由正则表达式文字创建的 RegExp 对象共享一个实例?

java - 在 Java 中使用非空白字符时 split 方法如何工作?

java - 使用java从数据之间提取子字符串的正则表达式

python - 编写函数来计算 panda 中的行元素的最佳方法是什么?

python - 提取维基百科中的所有城市

python - Django Mandrill 电子邮件编码

regex - 替换 Sublime Text 中的部分表达式?

java - 如何用 xml 包装(包围)java 匹配器组?