Unknown escape sequence - Regular expression

夙愿已清 提交于 2019-12-21 19:06:46

问题


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.



来源:https://stackoverflow.com/questions/6812206/unknown-escape-sequence-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!