Reputation: 17072
I have the following NSString:
var param1=8;
var param2=4;
var param3=1;
from which I need to extract the values of the params. I use the NSRegularExpression but cannot have it working:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"var param1=(.*);\nvar param2=(.*);\nvar param3=(.*)" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSString *param1= [match rangeAtIndex:1];
Upvotes: 1
Views: 4918
Reputation: 5539
Firstly, you're casting NSRange into NSString, last line should look like:
NSString *param1= [string substringWithRange:[match rangeAtIndex:1]];
And secondly, maybe something's wrong with your string? It could have white spaces before newline, etc. I've tested:
NSString *string = @"var param1=8;\n"
"var param2=4;\n"
"var param3=1;";
and it's working fine, returning an '8'.
Upvotes: 0
Reputation: 7563
while the title doesn't do justice to the answer, the question NSRegularExpression validate email supplies a link to a useful online regex checker .
my sense is that you are having trouble with the \n character in the regex in your example.
i would consider an expression such as @"^var param[123]=\b(\w*)\b;"
, which should provide you three matches; you'll have to use NSRegularExpression
method matchesInString
instead of firstMatchInString
, but your loop should be pretty simple:
NSArray* matches = [regex matchesInString:string
options:0
range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
// per match processing
}
Upvotes: 1