How to get URL inside @import statement by regexp

Viewed 145

I use this Reguler Expression to get @import statements of CSS Text if there is. This works successfully, for example:

RegExp:
(?:^|\s)?(?:@import)(?:\s)(?:url)?(?:(?:(?:\()(["'])?(?:[^"')]+)\1(?:\))|(["'])(?:.+)\2)(?:[A-Z\s])*)+(?:;)

Input:
@import url('https://meyerweb.com/eric/tools/css/reset/reset200802.css');@import url('http://opdetect.com/x/1-2-2.css');:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\",\"Segoe UI Symbol\",\"Noto Color Emoji\";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,\"Liberation Mono\",\"Courier New\",monospace}

Result:
@import url('https://meyerweb.com/eric/tools/css/reset/reset200802.css');
@import url('http://opdetect.com/x/1-2-2.css');

But, I want to result this like;

Expected Result:
https://meyerweb.com/eric/tools/css/reset/reset200802.css
http://opdetect.com/x/1-2-2.css

How can I do that?

3 Answers

You can use this regex, which is based on yours:

(?:^|\s)?(?:@import)(?:\s)(?:url)?(?:(?:(?:\()(["'])?(?:https?:)?([^"')]+)\1(?:\))|(["'])(?:.+)\2)(?:[A-Z\s])*)+(?:;)

I have changed a non capturing Group to a capturing Group, and created a new non capturing Group containing 'https?:'.

You need to set the 'global' flag.

Your desired result will be in Group 2.

Edit, based on your changed desired result ('http:' is now included in the match):

(?:^|\s)?(?:@import)(?:\s)(?:url)?(?:(?:(?:\()(["'])?([^"')]+)\1(?:\))|(["'])(?:.+)\2)(?:[A-Z\s])*)+(?:;)

Edit (found a mistake, changed the back reference):

(?:^|\s)?(?:@import)(?:\s)(?:url)?(?:(?:(?:\()(["'])?([^"')]+)\1(?:\))|(["'])(.+)\3)(?:[A-Z\s])*)+(?:;)

Your result will be in Group 2 OR Group 4.

How to use:

var input = 'your css';
var regex = / (?:^|\s)?(?:@import)(?:\s)(?:url)?(?:(?:(?:\()(["'])?([^"')]+)\1(?:\))|(["'])(.+)\3)(?:[A-Z\s])*)+(?:;)/g;
var matches = regex.exec(input);
for (var i = 0; i < matches.length; i++)
{
    var output = matches[i][2] + matches[i][4];  // one will be blank
    Console.WriteLine(output);
}

Maybe this can help you.

(https?:\/\/.+\.css)(?='\);@)|(http:\/\/.+\.css)

And you have your urls in group 1 and 2

Related