问题
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.
回答1:
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)
回答2:
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))
来源:https://stackoverflow.com/questions/41859419/regex-error-raise-error-v-invalid-expression