PYTHON REGEXP to replace recognized pattern with the pattern itself and the replacement?

江枫思渺然 提交于 2019-12-13 22:54:22

问题


Text-

.1. This is just awesome.2. Google just ruined Apple.3. Apple ruined itself! pattern = (dot)(number)(dot)(singlespace)

Imagine you have 30 to 40 sentences with paragraph numbers in the above pattern. A <p> tag should be replaced behind THE PARAGRAPH NUMBER! USING re.sub()

I want the text to be:

</p> <p style="text-align: justify;">1. This is just awesome.</p> <p style="text-align: justify;">2. Google just ruined Apple.</p> <p style="text-align: justify;">3. Apple ruined itself!

回答1:


This is what matching groups are for in regular expresssions.

What you want is something like this:

new_string = re.sub(r'\.(\d+\. )', '</p><p style="text-align: justify;">\\1', old_string)


来源:https://stackoverflow.com/questions/9278950/python-regexp-to-replace-recognized-pattern-with-the-pattern-itself-and-the-repl

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