Reputation: 362
I have a problem with reading the image path of a string like -> background-image:url(/assets/test.jpg)
I wanna have the string inside of the brackets without the brackets self.
Here is my code used:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bbackground-image:url\(.*\)\\b" options:NSRegularExpressionCaseInsensitive error:nil];
thumbnail = [regex stringByReplacingMatchesInString:thumbnail options:0 range:NSMakeRange(0, [thumbnail length]) withTemplate:@"$1"];
what i get is (/assets/test.jpg)
Upvotes: 1
Views: 918
Reputation: 1762
Use the following pattern to get the expeced result:
background-image:url\\((.*)\\)
Applied to your code:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"background-image:url\\((.*)\\)" options:NSRegularExpressionCaseInsensitive error:nil];
Using this the result will be "/assets/test.jpg", just as you want it to be.
Your code should have given you a warning about an unknown escape sequence for "\(". You have to use "\\(" to escape a "(". Also get rid of "\\b" at the beginning and end of your pattern.
But be aware that this pattern only works when your string only contains "background-image:url(somevaluehere)"
EDIT:
What does \\b mean?
\\b is a word boundary, usually expressed as \b. In an NSString you need to write \\b because you need to escape the \ so it will be treated as real backslash.
Here some information on what word boundaries match:
There are three different positions that qualify as word boundaries:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".
Taken from http://www.regular-expressions.info/wordboundaries.html
I hope this clarifies this a bit.
Upvotes: 3
Reputation: 1714
I believe you should change your regex to \\bbackground-image:url\((.*)\)\\b
.
I added () around .* to capture the match you want.
Upvotes: 0