Reputation: 43
I am working on an iOS project that require using regular expression to validate ipv4 address.
I use following code
// only support ip4 currently
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
options:0
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:IpString options:0 range:NSMakeRange(0, [IpString length])];
return (numberOfMatches==1?TRUE:FALSE);
XCode keep warning me "unknown escape sequence .". When return true when I type "1.3.6.-6" or "2.3.33".
How can I use dot(.) in regex? Thanks
Upvotes: 2
Views: 1975
Reputation: 19030
You need to double backslash your .
, as the first backslash is being interpreted by NSString, and it's looking for an escape character for .
(which doesn't exist). Double backslashing (\\.
) will cause the first backslash to escape the second backslash (which does exist), meaning you can use \
normally.
So for example, your regex will be:
@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
Upvotes: 4