Unknown escape sequence - Regular expression

2020-07-17 15:13发布

问题:

I want to validate email text for which I am using RegexKitLite.h. I am doing things as follows :

NSString *strEmail = [txtEmail text];
                NSRange range = [strEmail rangeOfRegex:@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"];
                NSLog(@"%@",range);  

For now I am just checking if this works. But I am getting error in second line. Log doesn't say anything. But there is a warning in second line which says :

Unknown escape sequence '\.'  

What might be the problem? Is there something wrong in expression or is there some other issue?

回答1:

You don't need to escape the dot in a character class. Most regex engines ignore this kind of error, Objective C's seems to be more strict. Try this:

rangeOfRegex:@"^[a-zA-Z][\w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z.]*[a-zA-Z]$"

However (and unrelated to the problem), that's a fairly strange e-mail validation regex as it will reject many valid e-mail addresses and allow many invalid ones. I don't know what you're aiming for here, but it is generally a good idea not to be too strict with validating regexes and rather do the validation by actually sending an e-mail to that address and see if it fails.