I have the following Python code:
string = '[subscript=hello] this is some text [subscript=hi again]'
superscripts = re.findall(r'\[subscript=(.+?)\]', string)
print superscripts
and it returns ['hello', 'hi again']
which is the text which I want, however, I would rather instead of returning this, I would prefer it to replace the string so that it returns <sub>hello</sub> this is some text <sub>hi again<sub>
. I know I should use re.sub() but I'm unsure how to use it to correctly replace the string to my liking.
How would I do this? Thanks.
Edit: Screenshots
答案 0 :(得分:5)
Use a backreference \1
which refers to the matched group in the first argument in your pattern:
your_new_string = re.sub(r'\[subscript=(.+?)\]', r'<sub>\1</sub>', your_old_string)