【问题标题】:Python search for character pattern and if exists then indentPython搜索字符模式,如果存在则缩进
【发布时间】:2026-01-03 17:10:01
【问题描述】:

我想找到一个文本模式并将其推送到新行。模式是),,后跟一个空格和一个字符。像这样-

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) (demo) 或者,如果它应该在一行的开头,re.sub(r'^\),[^\S\n]*(?=\w)', '),\n', text_orig, flags=re.M)
  • 缩进是你添加标签时所做的。实际上,您似乎只想在找到该模式的位置添加换行符。
  • @PranavHosangadi 啊是的,然后在找到模式的地方换行
  • 您正在寻找的术语(Wiktor 的示例使用)称为“正向前瞻”。 *.com/questions/47886809/… 例如,正则表达式ab(?=c) 将匹配包含"abc" 的字符串,但不会将"c" 作为匹配的一部分使用

标签: python regex search str-replace re


【解决方案1】:

你可以使用

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) - 正向前瞻,需要在当前位置右侧紧接一个字符字符。

【讨论】:

  • 这很好,谢谢你的解释
最近更新 更多