baked182
baked182

Reputation: 45

Use Regex to remove characters between certain character

I am trying to change a string so that anything in between the * character is removed

For example, the string [xyz] - * remove this. . * Abcd123 should become [xyz] - Abcd123.

Another example: abc*def*ghi should become abcghi

This is my code, I am trying to keep any character that is not * but I don't think I am writing it correctly:

str = '[xyz] - * remove this. . *  Abcd123'

regex = re.compile('^(\*.*\*)+')
mo = regex.findall(str)

Upvotes: 0

Views: 1093

Answers (3)

M Z
M Z

Reputation: 4799

Check out re.sub

import re

str = '[xyz] - * remove this. . *  Abcd123'

res = re.sub(r"\*[^\*]*\*", '', str)

Depending on what you need, you might want the G and M flags.

If you have several occurrences of *....*, this will take care of that. It will also make sure not to accidentally remove too much: for example, if you had *....*....*, this would consider only consecutive * for making pairs, not just looking at the first and the last *.

Upvotes: 3

Tsubasa
Tsubasa

Reputation: 1429

First Method

import re

s_1 = '[xyz] - * remove this. . *  Abcd123'
s_2 = 'abc*def*ghi'

reg = re.compile(r'\*.*\*')

print(reg.sub('', s_1))
print(reg.sub('', s_2))

How does this regex work?

This \* selects the asterisk '*'. Then we're selecting zero or more of everything within the two asterisk '*' using .*.

Second Method

s_1 = '[xyz] - * remove this. . *  Abcd123'
s_2 = 'abc*def*ghi'

print(''.join(s_1.split('*')[::2]))
print(''.join(s_2.split('*')[::2]))

Here we're basically splitting the code on '*' and then removing the part within the asterisks.

Upvotes: 2

Divin Irakiza
Divin Irakiza

Reputation: 357

You can do it without using regex. Try this:

str = 'abc*def*ghi'
replace = str[:(str.index('*'))] + str[(str.rfind('*') + 1):]
print(replace)

.index() -> Finds the first occurence of the character in a string
.rfind() -> Finds the last occurence of a character in a string

Upvotes: 2

Related Questions