英文:
Make a regular expression in the search in VS code
问题
I'd like to change the img html tag to django html with {% static %}
.
Can you make a regular expression in the ctrl + f function so I can change it at once?
Example:
<img src="../img/logo.png"
=> <img src="{% static 'img/logo.png' %}"
r'<img\s+src="(.*?)"'
But I can't find a way to change the code while preserving the middle values.
英文:
I'd like to change the img html tag to django html with {%static
.
Can you make a regular expression in the ctrl + f function so I can change it at once?
Example:
<img src="../img/logo.png"
=> <img src=" {%static 'img/logo.png' %}"
r'<img\s+src="(.*?)"'
But I can't find a way to change the code while preserving the middle values
答案1
得分: 2
你可以使用反向引用来处理:
搜索查询:<img\s+src="[.][.]/([^"]*)"
<br>
替换为:<img src="{% static '$1' %}"
然后,$1
将被替换为第一个捕获组。
话虽如此,HTML 是一种无上下文的语言。这意味着大多数任务不能(完美地)通过正则表达式来处理。例如,我们在这里创建的正则表达式没有考虑到 src=""
属性之前的属性。因此,像 BeautifulSoup 这样的工具可能是更好的选择。
英文:
You can work with a backreference:
search query: <img\s+src="[.][.]/([^"]*)"
<br>
replace with: <img src="{% static '$1' %}"
The $1
will then be replaced with the first capture group.
That being said, HTML is a context-free language. That means most tasks can not be handled (perfectly) with a regular expression. For example the regex we here make does not take into accounts attributes before the src=""
attribute. Likely a tool like BeautifulSoup is therefore a better idea.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论