I need a single regex to capture the relative path /image/picture/name.jpg from the below 3 similar strings. I tried many ways but there are some vulnerabilities in my regex code which is making it to work inconsistently. I couldn't find any perfect soluti开发者_开发问答on for this specific issue. Any help is Greatly appreciated.
- string 1 : url(/image/picture/name.jpg)
- string 2 : url("/image/picture/name.jpg")
- string 3 : url('/image/picture/name.jpg')
This should capture the URL into group 1:
url\(((?:"|')?)([a-z/\.]*?)\1\)
It will also capture anything else within the URL tag's brackets that looks like a URL but is nice and specific to the case...
This will catch the cases you mention, though it's a little on the expensive side:
(?ix-:url\(\s*
(?:
(?<url>[^\)'"][^\)]*[^\)\s]) |
(?:'(?<url>[^']*)') |
(?:"(?<url>[^"]*)")
)\s*
\))
Rather I would use the following and then test for and trim the quotes manually:
url\(\s*(?<url>[^)'"][^\)]*[^\)\s])\s*\)
The down-side to the later expression is that it does not correctly handle the quoted close parenthesis ')' character as in the following example:
String: url( '/images/logo Copy(2).jpg' )
Try this:
url(("|')?/image/picture/name.jpg("|')?)
If I understand you correctly and you want everything inside the parentheses but not quotes to be included the following statement should do. It will of course not accept numbers etc, but will return enything from the first slash encountered until the last character not a slash or alpha-character.
Regex re = new Regex(@"/([a-z/.])*", RegexOptions.IgnoreCase);
Try this:
url\(['"]?(?<url>[^'")])['"]?\)
The exact url could be matched in group named "url"
精彩评论