1

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];
Luc
  • 16,604
  • 34
  • 121
  • 183

2 Answers2

1

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
    }
Community
  • 1
  • 1
john.k.doe
  • 7,533
  • 2
  • 37
  • 64
0

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'.

Johnnywho
  • 5,541
  • 2
  • 27
  • 20