Kabir
Kabir

Reputation: 99

Regex to find css reference

1. <link href="~/styles/test.css?v=15" rel="stylesheet" />
2. <link href="../styles/test.css?v=15" rel="stylesheet" />
3. <link href="~/styles/test.css" rel="stylesheet" />
4. <link href="../styles/test.css" rel="stylesheet" />
5. <link href="https://static.content.com/styles/test.css" rel="stylesheet" />
6. <link href="@Url.Content("~/styles/test.css")" rel="stylesheet" type="text/css" />
7. <link href="@Url.Content("../styles/test.css")" rel="stylesheet" type="text/css" />
8. <link href="@Url.Content("https://static.content.com/styles/test.css")" rel="stylesheet" type="text/css" />
9. <link type="text/css" rel="stylesheet" 
href='<%= Page.ResolveClientUrl("~/styles/test.css") %>' />
10. <link type="text/css" rel="stylesheet" 
href='<%= Page.ResolveClientUrl("../styles/test.css") %>' />

In all the above case, I should get value inside inverted comas like

~/styles/test.css?v=15
../styles/test.css?v=15
~/styles/test.css
../styles/test.css
https://static.content.com/styles/test.css

Can I get a single Regex for this? I just want value inside inverted comas and not anything other than that, not even inverted comas and css can be referred from other folders like content and not only styles. so please do not provide Regex, which looks like hard coding. There can be many syntax for referring the css, I should not change Regex for every syntax.

Upvotes: 1

Views: 496

Answers (2)

zx81
zx81

Reputation: 41838

EDIT: Krishna has added a new context in which he wants to match css, so the regex has been expanded accordingly.

In most standard regex flavors, I would use this:

(?<=ResolveClientURL\(")[^"]+|(?:(?<=<link href=")(?!@Url\.Content)|(?<=<link href="@Url\.Content\("))(?:[^"])+

The left side of the alternation handles the last case you added by using a lookbehind.

On the other side of the alternation, the first set of parentheses contains an alternation | with two sets of lookarounds, one for each of our two cases.

The first one asserts: "at this position in the string, the string <link href=" is behind me, and the string @Url\.Content is not in front of me.

After the OR (|), the second one asserts: "at this position in the string, the string <link href="@Url\.Content\(" is behind me.

Having asserted either of those, we know we just passed the opening double quote.

The (?:[^"])+ eats up any character that is not a double quote, thereby eating up everything up to the closing "

Upvotes: 1

aelor
aelor

Reputation: 11116

use this :

"((?:https?|\.{2}|~).*?\/styles.*?)"

demo here : http://regex101.com/r/iJ4oT7

Upvotes: 0

Related Questions