删除两个字符之间的所有内容,包括字符

时间:2014-08-07 19:44:32

标签: python regex

string = "$hahahaha$hahahaha hello";

如何删除2 $和$&之间的所有内容,以便我最终:

hahahaha hello

$也可能是' @'或' *'或者'&'或者'?'

6 个答案:

答案 0 :(得分:3)

如果您不习惯使用正则表达式,可以使用find()方法。请检查以下代码:

>>> string = "$hahahaha$hello"
>>> ch = '$'
>>> pos_1 = string.find(ch)
>>> if pos_1 < len(string) - 2:
...   pos_2 = string[pos_1+1:].find(ch) + pos_1 + 1
... 
>>> if pos_2 < len(string) - 1:
...   string = string[0:pos_1] + string[pos_2+1:]
... else:
...   string = string[0:pos_1]
... 
>>> string
'hello'
>>> 

答案 1 :(得分:2)

使用正则表达式

import re

string = "$hahahaha$hahahaha hello"
stripped = re.sub("[$@*&?].*[$@*&?]", "", string)
print stripped

应输出

hahahaha hello

答案 2 :(得分:1)

import re
string = "$hahahaha$hello";
ma = re.search(r'([$@*&?])(.+)\1(.+)$', string)
print ma.group(2), ma.group(3)

答案 3 :(得分:1)

您可以使用以下正则表达式:

([$@*&?]).*?\1(.*)

<强> Working demo

抓住第二个捕获组

enter image description here

答案 4 :(得分:0)

import re
text = "$hahahaha$hahahaha hello"
print text.replace(re.findall(r'\$(.*?)\$', text)[0],'').replace('$','')

但需要扩展除$以外的其他字符以及$字符之间的多个字符串。

答案 5 :(得分:0)

In [42]: s = "$hahahaha$hahahaha hello"

In [43]: " ".join(s.rsplit("$",1)[1:])
Out[43]: 'hahahaha hello'

In [44]: (re.split("[$@*&?]",s)[-1])
 Out[44]: 'hahahaha hello'