Ryk Waters Ryk Waters - 3 months ago 12
CSS Question

What regex to match all occurrences of css urls?

i have a css file with a bunch of background image urls:

.alert-01 {
background: url('img/alert-01.jpg') center no-repeat;
}
.alert-02 {
background: url('img/alert-02.jpg') center no-repeat;
}
.alert-03 {
background: url('img/alert-03.jpg') center no-repeat;
}
.alert-04 {
background: url('img/alert-04.jpg') center no-repeat;
}


And I'd like to write a regex that would strip out the urls.

So initially i would get:

url('img/alert-01.jpg')
url('img/alert-02.jpg')
url('img/alert-03.jpg')
url('img/alert-04.jpg')


Which i could then replace bits to turn them into html
<img>
blocks.

I'm fine with the last bit, but my regex skills are a bit rusty.

My latest try was this:
/^url\(.*?g\)$/ig


Any help?

BTW I was doing this all in javascript, but the language shouldn't affect the regex really.

Thanks in advance!

Also, just to note, i can't guarantee that the files will always be jpg and may be jpeg, png etc. Also that the arguments into background will always be the same. Hence why i want to extract just the url part.

Answer

Try:

/url\(.*?g'\)/ig

Your mistake was including ^ and $ in the regexp, which anchors it to the beginning and end of the input string. And you forgot to allow for the quote.

Comments