Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用正则表达式从多行字符串中删除特定字符_Python_Regex - Fatal编程技术网

如何在python中使用正则表达式从多行字符串中删除特定字符

如何在python中使用正则表达式从多行字符串中删除特定字符,python,regex,Python,Regex,我有一个多行字符串,如下所示: st = '''emp:firstinfo\n :secondinfo\n thirdinfo ''' print(st) '''emp:firstinfo\n secondinfo\n thirdinfo ''' 我试图做的是跳过字符串中的第二个“:”,并获得如下输出: st = '''emp:firstinfo\n :secondinfo\n thirdinfo

我有一个多行字符串,如下所示:

st = '''emp:firstinfo\n
       :secondinfo\n
       thirdinfo
     '''
print(st)
'''emp:firstinfo\n
   secondinfo\n
   thirdinfo
   '''
我试图做的是跳过字符串中的第二个“:”,并获得如下输出:

st = '''emp:firstinfo\n
       :secondinfo\n
       thirdinfo
     '''
print(st)
'''emp:firstinfo\n
   secondinfo\n
   thirdinfo
   '''
简单地说,如果它以“:”开头,我试图忽略它

以下是我所做的:

mat_obj = re.match(r'(.*)\n*([^:](.*))\n*(.*)' , st)
print(mat_obj.group())

显然,我看不出我的错误,但有谁能帮我告诉我哪里出了错吗?

您可以将
re.sub
用于此正则表达式:

>>> print (re.sub(r'([^:\n]*:[^:\n]*\n)\s*:(.+)', r'\1\2', st))
emp:firstinfo
secondinfo

       thirdinfo

正则表达式详细信息:

  • :启动第一个捕获组
    • [^:\n]*
      :匹配0个或更多非
      字符和换行符
    • :匹配冒号
    • [^:\n]*
      :匹配0个或更多非
      字符和换行符
    • \n
      :匹配新行
  • :结束第一个捕获组
  • \s*
    :匹配0个或多个空格
  • :匹配冒号
  • (.+)
    :匹配第二个捕获组中的一个或多个字符(换行符除外)
  • \1\2
    :用于替换以放回在组1和组2中捕获的子字符串

您可以改用sub,只是不要捕获不需要的部分

(.*\n)[^:]*:(.*\n)(.*)

取而代之

\1\2\3


进口稀土

#remove character in a String and replace with empty string. 
text=“电影《低俗小说》于1994年发行” 结果=re.sub(r“[a-z]”,“”,文本)
打印(结果)

要删除的
位置的具体区别是什么?它是否总是字符串中的第二个