lmirosevic
lmirosevic

Reputation: 16317

what's wrong with this simple regex in Cocoa

It's a simple regex and I've tried using a few of the online testing tools and it works but when I run it in code, it doesn't.

BEGIN EDIT: It doesn't find any match at all. What I am trying to do is check if a line in a configuration file contains the http setting. So if a line is extraintf= I want to change it to extraintf=http, if the line is extraintf=rc:ncurses, I want to change it to extraintf=rc:ncurses:http, and if the line is #extraintf= I want to change it to extraintf=http. I am using a regex to find the location and length of that line, once I have the start and length of the line I wrote some tested and working code that will do the above fine, it's just finding the range of the match that is the problem. END EDIT

Here's my regex:

^#?extraintf=.*$

I want it find the middle line in all of these files:

File1:

# Interface module (string)
#intf=

# Extra interface modules (string)
extraintf=                                    //match this line

# Control interfaces (string)
#control=

File 2:

# Interface module (string)
#intf=

# Extra interface modules (string)
extraintf=rc                                    //match this line

# Control interfaces (string)
#control=

File 3:

# Interface module (string)
#intf=

# Extra interface modules (string)
#extraintf=                                    //match this line

# Control interfaces (string)
#control=

And then the way I check for a match is using:

//check if file exists
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory];

if (isDirectory || !fileExists) {
    return;
}

//get the settings file
NSError *error;
NSString *settingsString = [NSString stringWithContentsOfFile:fullPath encoding:NSMacOSRomanStringEncoding error:&error];


NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^#?extraintf=.*$" options:NSRegularExpressionCaseInsensitive error:NULL];

NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:settingsString options:0 range:NSMakeRange(0, [settingsString length])];

if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
    //got a match
}
else {
    //no match
}

Upvotes: 2

Views: 408

Answers (2)

epatel
epatel

Reputation: 46051

You need to add NSRegularExpressionAnchorsMatchLines to the options. This will allow ^ and $ to match the start and end of lines.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^#?extraintf=.*$" 
                              options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines 
                              error:NULL];

Upvotes: 4

sergio
sergio

Reputation: 69027

Have you tried loosening the match like this?

"^[^e]?extraintf=.*$"

Upvotes: 0

Related Questions