I have to replace a substring with another string in a file.
Below is the line which is present in the file.
Input: #pragma MESSAGE "Hello World" 0000=1 /* Clarification 0001: [[Specific Clarification]] */
Expected Output: #pragma MESSAGE "Hello World" 0000=1 # [[Specific Clarification]]
Below is my code:
import re
line = r'#pragma MESSAGE "Hello World" 0000=1 /* Clarification 0001: [[Specific Clarification]] */'
comment = re.search(r'([\/\*]+).*([^\*\/]+)', line)
replace = re.search(r'([\[[]).*([\]]])', comment.group())
replaceWith = replace.group()
content_new = re.sub(r'([\/\*]).*([\*\/])', '# ' + replaceWith, line)
Is there an optimal solution for the above code?
content? What is the problem with the regex? If you need to replace, why do you usere.search, and even twice?contentwithline. Is there any alternative way to approach this problem with one regex statement?content_new = re.sub(r'/\*(.*?)\*/', lambda x: re.sub(r'.*(\[\[.*?]]).*', r'# \1', x.group(1)), line), see demo.