regex error : raise error, v # invalid expression

冷暖自知 提交于 2021-01-29 04:37:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!