1

I have a variable device='A/B/C/X1' that is commented out in another file. There can be multiple instances of the same device such as 'A/B/C/X1@1', ..@2 and so on. All of these devices are commented out in another file with a prefix *.

I want to remove the * but not affect similar devices like 'A/B/C/X**10**'.

I tried using regex to simply substitute a pattern using the following line of code, but I'm getting an InvalidExpression error.

line=re.sub('^*'+device+'@',device+'@',line)

Please help.

Tagc
  • 8,736
  • 7
  • 61
  • 114

2 Answers2

3

You need to escape the asterisk since it has a meaning in regex syntax: line=re.sub(r'^\*'+device+'@',device+'@',line).

Escaping the variables you use to construct the regex is also always a good idea: line=re.sub(r'^\*'+re.escape(device)+'@',device+'@',line)

Martin Valgur
  • 5,793
  • 1
  • 33
  • 45
0
def replace_all(text):
    if text in ['*']:
        text = text.replace(text, '')
    return text

my_text = 'adsada*asd*****dsa*****'

result = "".join(map(replace_all, my_text))
print result

Or

import re
my_text = 'adsada*asd*****dsa*****'
print (re.sub('\*', '', my_text))
4b0
  • 21,981
  • 30
  • 95
  • 142
Tim Uzlov
  • 181
  • 2
  • 6