Python搜索字符模式,如果存在则缩进 [英] Python search for character pattern and if exists then indent

查看:51
本文介绍了Python搜索字符模式,如果存在则缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pattern of text that I would like to find and push to a new line. The pattern is ), followed by a space and a character. Like this -

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 但我相信会像这样删除文本的第一个字母 -

I'm pretty close to a solution, but stuck on what approach to use. Currently, I'm using re.sub but I believe that removes the first letter of the text like so -

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 吗?非常感谢帮助

Would I need search instead of sub? Help is very appreciated

推荐答案

可以使用

re.sub(r'\),[^\S\n]*(?=\w)', '),\n', text_orig)

查看正则表达式演示.

或者,如果模式只应在行首匹配,则应添加 ^re.M 标志:

Or, if the pattern should only match at the start of a line, you should add ^ and the re.M flag:

re.sub(r'^\),[^\S\n]*(?=\w)', '),\n', text_orig, flags=re.M)

这里,

  • ^ - 一行的开始(带有 re.M 标志)
  • \), - ), 子串
  • [^\S\n]* - 除 LF 字符外的零个或多个空格
  • (?=\w) - 正向前瞻,需要在当前位置右侧紧接一个字符字符.
  • ^ - start of a line (with re.M flag)
  • \), - a ), substring
  • [^\S\n]* - zero or more whitespaces other than LF char
  • (?=\w) - a positive lookahead that requires a word char immediately to the right of the current location.

这篇关于Python搜索字符模式,如果存在则缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆