在VS Code中创建一个正则表达式搜索。

huangapple go评论80阅读模式
英文:

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

你可以使用反向引用来处理:

搜索查询:&lt;img\s+src=&quot;[.][.]/([^&quot;]*)&quot;<br>
替换为:&lt;img src=&quot;{% static &#39;$1&#39; %}&quot;

然后,$1 将被替换为第一个捕获组

话虽如此,HTML 是一种无上下文的语言。这意味着大多数任务不能(完美地)通过正则表达式来处理。例如,我们在这里创建的正则表达式没有考虑到 src=&quot;&quot; 属性之前的属性。因此,像 BeautifulSoup 这样的工具可能是更好的选择。

英文:

You can work with a backreference:

search query: &lt;img\s+src=&quot;[.][.]/([^&quot;]*)&quot;<br>
replace with: &lt;img src=&quot;{% static &#39;$1&#39; %}&quot;

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=&quot;&quot; attribute. Likely a tool like BeautifulSoup is therefore a better idea.

huangapple
  • 本文由 发表于 2023年7月24日 16:09:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定