Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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)
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.