How can I tell this regex expression to ignore www urls and catch both ('Inter.ttf') and (Inter.ttf)

Viewed 43

so I currently have a regex expression which replaces css urls by appending '/static/user' to each url. However, I want to make this expression ignore www urls (https://www.google.com) and catch both instances of url('Inter-Black.ttf') and url(Inter-Black.ttf), with and without quotation marks.

This is my current code:

p = re.compile(r"(?<=url\(')/?(?=(?:.*?\.\w{3})'\))")
filez = re.sub(p, '/static/user/', filez)

I have also tried which does not work.

p = re.compile(r"^(?!.*(www))(?<=url\(')/?(?=(?:.*?\.\w{3})'\))")
filez = re.sub(p, '/static/user/', filez)

And currently use this solution in order to catch both quotes and non quotes. But ideally I would want a cleaner solution along with regex ignoring www urls.

p = re.compile(r"(?<=url\(')/?(?=(?:.*?\.\w{3})'\))")
filez = re.sub(p, '/static/user/', filez)
p = re.compile(r"(?<=url\()/?(?=(?:.*?\.\w{3})\))")
filez = re.sub(p, '/static/user/', filez)

Thank you for your time.

2 Answers

You might use an optional capture group with an if clause to account for the opening ' matching with a closing '

(url\()(?!https?://www\.google\.com)(')?/?([^()']*)((?(2)')\))

The pattern matches:

  • (url\() Capture group 1, match url(
  • (?!https?://www\.google\.com) Negative lookahead, assert not the specific url
  • (')? Optionally capture ' in group 2
  • /? Optionally match a leading /
  • ([^()']*) Capture group 3, match any char except ( ) or '
  • ( Capture group 4
    • (?(2)') If clause to check if group 2 exists, if it does, match '
    • \) Match )
  • ) Close group

Regex demo | Python demo

import re

filez = """url(https://www.google.com)
url('Inter-Black.ttf')
url(Inter-Black.ttf)
url('Inter-Black.ttf)
url('/fonts/user/Inter-Black.ttf')
url('/fonts/user/mywebsite/Inter-Black.ttf')
"""

p = r"(url\()(?!https?://www\.google\.com)(')?/?([^()']*)((?(2)')\))"
filez = re.sub(p, r"\1\2/static/user/\3\4", filez)
print(filez)

Output

url(https://www.google.com)
url('/static/user/Inter-Black.ttf')
url(/static/user/Inter-Black.ttf)
url('Inter-Black.ttf)
url('/static/user/fonts/user/Inter-Black.ttf')
url('/static/user/fonts/user/mywebsite/Inter-Black.ttf')

Hope to help

import re

filez = """url(https://www.google.com)
url('Inter-Black.ttf')
url(Inter-Black.ttf)
"""


p = re.compile(r"(url\(\'?)((?!.*www).*\.\w{3})(\'?\))")

filez = re.sub(p, r'\1/static/user/\2\3', filez)

print(filez)

output:

url(https://www.google.com)
url('/static/user/Inter-Black.ttf')
url(/static/user/Inter-Black.ttf)
Related