views:

47

answers:

4

Hi,

I'm trying to get the url portion of the following string:

url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)

So the required part if images/ui-bg_highlight-soft_75_cccccc_1x100.png.

Currently I've got this:

url\((?<url>.*)\)

But it seems to be choking on the following example:

url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30)

Which results in images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30...

I'd like to make sure that it supports as many variations as possible (additional whitespace etc).

Thanks!
Kieron

Edit

Additionally, I need to ignore the optional quotes ' or " ...

Now, it looks like this:

url\(['|"]?(?<url>[^)]+)\)

I can't seem to get it to stop/ ignore the last quote...

+1  A: 

Replace .* with [^\)]+

zerkms
Brilliant, thanks!
Kieron
+3  A: 

This is due to the greediness of the * quantifier, try a negated character class instead of a .

url\((?<url>[^)]*)\)

or you could use the lazy operator

url\((?<url>.*?)\)

First choice is proabably better.

Edit: To ignore the second quote, you will want to use the lazy quantifier like this

url\(['"]?(?<url>[^)]+?)['"]?\)

You don't use the alternation meta character | within a character class.

Paul Creasey
I thought it would be something like that, reg-ex is one of those things that I have to re-learn every time I use it - even if it's been 10mins since I last did any. Thanks for the help.
Kieron
@Kieron: once you decide to solve trouble with regex - you have 2 troubles ;-)
zerkms
This, I know (:
Kieron
Updated, Regex is great really, just so often abused and misunderstood!
Paul Creasey
>> To ignore the second quote --- just put another char to excluding set [^\)']
zerkms
Perfect, thankyou!
Kieron
A: 

url\((.*\.png)

url\((.[^)]*)\)

bergin
The example above is just an example, it needs to be able to match anything.
Kieron
doh yes of course.url\\((.[^)]*)\\)
bergin
A: 

This should do it:

url\(['"]?(?<url>.*?)['"]?\)

But you might want to allow for optional whitespace:

url\s*\(['"\s]*(?<url>.*?)['"\s]*\)

That will also match some invalid strings, but that shouldn't be a problem if your CSS is valid.

On more thing: that | in ['|"] does not act as an OR operator, it just matches a literal |. OR is implicit in character classes.

Alan Moore