相关文章推荐
失眠的烤红薯  ·  python qt textBrowser ...·  4 周前    · 
帅气的领带  ·  【Pyspark ...·  1 周前    · 
近视的橙子  ·  python ...·  1 周前    · 
眉毛粗的电梯  ·  python ...·  15 小时前    · 
打盹的手链  ·  用Applescript ...·  1 年前    · 
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)

For the record it has a special meaning in markdown too OP. That's why you had random italics and bolded text all over the place. – Tagc Jan 25, 2017 at 19:02 @Emaro That will not be sufficient since it will only disable unescaping of backslashes in that string, nothing more. – Martin Valgur Jan 25, 2017 at 19:04

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.