How do I escape special characters in an NSString using RegexKitLite?

て烟熏妆下的殇ゞ 提交于 2019-12-06 06:22:36

问题


I'm constructing a regular expression that uses strings input by the user but the strings might contain special characters such as . \ or * and I want those to be treated as literals and not interpreted by their special meanings in the regex. I've tried this:

NSString *word = [input stringByReplacingOccurrencesOfRegex:@"(\\P{L})" withString:@"\\$1"];

but the non letter characters are converted to '$1' instead of being prefixed with a backslash. I've tried one and three backslashes in the second term but those give me an 'Unknown escape sequence' warning in XCode. How can I print a backslash without RegexKitLite thinking that I'm escaping the dollar sign?


回答1:


Write the expression as you normally would and then replace each single backslash with two. Thus

\. 

becomes

\\. 

and

\\ 

becomes

\\\\


来源:https://stackoverflow.com/questions/4354606/how-do-i-escape-special-characters-in-an-nsstring-using-regexkitlite

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