我有一个文本模式,我想找到它并推到一个新行。模式是 ),
后跟一个空格和一个字符。像这样 -
text_orig =
text cat dog cat dog
),
text rabbit cat dog
), text coffee cat dog. #need to indent this line
它会变成什么地方
text_new =
text cat dog cat dog
),
text rabbit cat dog
),
text coffee cat dog
我非常接近解决方案,但坚持使用哪种方法。目前,我正在使用 re.sub
但我相信这样会删除文本的第一个字母 -
text_new =
text cat dog cat dog
),
text rabbit cat dog
),
ext coffee cat dog # removes first letter
re.sub('\),\s\w','), \n',text_orig)
我需要 search
而不是 sub
吗?非常感谢帮助
最佳答案
你可以使用
re.sub(r'\),[^\S\n]*(?=\w)', '),\n', text_orig)
参见 regex demo .
或者,如果模式应该只在一行的开头匹配,您应该添加 ^
和 re.M
标志:
re.sub(r'^\),[^\S\n]*(?=\w)', '),\n', text_orig, flags=re.M)
这里,
^
- 行首(带有re.M
标志)\),
-),
子串[^\S\n]*
- 除 LF 字符外的零个或多个空格(?=\w)
- 一个积极的前瞻,需要紧靠当前位置右侧的单词 char。
关于Python搜索字符模式,如果存在则缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66805321/