Unknown escape sequence - Regular expression

2020-07-17 15:07发布

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条回答
可以哭但决不认输i
2楼-- · 2020-07-17 15:25

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.

查看更多
登录 后发表回答