Search code examples
pythonregexdjangopycharm

Regular expression to replace all script src attributes


I need to refactor existing Django code, by using {% static 'path/to/file' %} tag. I think it's possible to use PyCharm feature "Replace in path" with regex option.

So, I need to replace my script tags, which now look like:

<script type="text/javascript" src="/static/js/script.js"></script>

To look like:

<script type="text/javascript" src="{% static 'js/script.js' %}"></script>

Here is PyCharm "Replace in Path" window:

enter image description here

I think I should pass in "Text to find" something like src="([^"]+)", but what should I pass in "Replace with", I can't understand.


Solution

  • Simplified version of your regex would be src="(.+?)". Instead, you can use the following expression to match

    src="/static/(.+?)"
    

    And replace with

    src="{% static '$1' %}"