Harry
Harry

Reputation: 13329

Remove everything between two characters including the characters

string = "$hahahaha$hahahaha hello";

How can I remove everything between the 2 $'s and also the $'s so I end up with:

hahahaha hello

The $ could also be '@' or '*' or '&' or '?'

Upvotes: 4

Views: 21036

Answers (6)

Federico Piazza
Federico Piazza

Reputation: 30985

You can use the following regex:

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

Working demo

And grab the 2nd capturing group

enter image description here

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

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'

Upvotes: 0

Tamim Shahriar
Tamim Shahriar

Reputation: 739

If you are not comfortable using regular expression, you can use find() method. Please check the following code:

>>> 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'
>>> 

Upvotes: 3

philshem
philshem

Reputation: 25331

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

but needs to be expanded for other characters besides $ and for multiple strings between the $ character.

Upvotes: 0

Tag Groff
Tag Groff

Reputation: 177

use a regular expression

import re

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

should output

hahahaha hello

Upvotes: 6

user590028
user590028

Reputation: 11730

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

Upvotes: 1

Related Questions