[英]Python Regex - search and replace matches
Vivamus sagittis lacus (name: something) vel augue laoreet
rutrum faucibus dolor auctor. Donec ullamcorper nulla (name: another_thing)
metus auctor fringilla.
這是我的繩子。 可能有多種模式,例如(name: xxxx)
。 我想找到它們中的每一個並替換為: <a href="something">something</a>
因此,專門針對此示例,新字符串應類似於:
Vivamus sagittis lacus <a href="something">something</a> vel augue laoreet
rutrum faucibus dolor auctor.
Donec ullamcorper nulla <a href="another_thing">another_thing</a>
metus auctor fringilla.
在大多數情況下,一個簡單的re.sub
就足夠了:
import re
newstring = re.sub(r'\(name:\s*([^)]+)\)',
r'<a href="\1">\1</a>',
old_string)
但是,這假定該name
在語法上可以作為HTML href
屬性使用(不包含雙引號,括號和&c)。 如果該假設不成立,那么工作將變得更多:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.