What regex to match all occurrences of css urls?

后端 未结 6 2184
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 14:36

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(\'         


        
6条回答
  •  渐次进展
    2021-02-20 14:48

    Using a tool like Regexper we can see what your regular expression is matching:

    Regex Image

    As you can see there are a few problems with this:

    1. This assumes "url(" is at the start of the line.
    2. This assumes the content ends with "g)", whereas all of your examples end with "g')".
    3. This assumes after "g)" is the end of the line.

    What we instead need to do is match just "url(" [any character] ")". And we can do that using:

    /url\(.*?\)/ig
    

    Fixed Regex

    Note that I've removed the requirement for the URL ending in "g" in case the image type is .gif or any other non-jpg, jpeg or png.


    Edit: As Seçkin M commented below: what if we don't want any other url's; such as fonts which have .ttf or .eot? What is the easiest way to define an allowed extensions group?

    For this we can predefine what extensions we're looking for by putting our extensions within brackets, separated with |. For instance, if we wanted to match only gif, png, jpg or jpeg, we could use:

    /url\(.*?(gif|png|jpg|jpeg)\'\)/ig
    

    Amended Fix

提交回复
热议问题