如何使用RegexKitLite转义NSString中的特殊字符? [英] How do I escape special characters in an NSString using RegexKitLite?

查看:269
本文介绍了如何使用RegexKitLite转义NSString中的特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构造一个使用用户输入的字符串的正则表达式,但字符串可能包含特殊字符,例如。 \或*,我希望这些被视为字面值,而不是通过它们在正则表达式中的特殊含义来解释。我试过这个:

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"];

但非字母字符将转换为$ 1,而不是以反斜杠作为前缀。我在第二个期间尝试了一个和三个反斜杠,但是这些在XCode中给我一个未知的转义序列警告。如何在没有RegexKitLite的情况下打印反斜杠,认为我要转义美元符号?

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?

推荐答案

然后用两个替换每个单个反斜杠。因此

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

\. 

成为

\\. 

\\ 

成为

\\\\

这篇关于如何使用RegexKitLite转义NSString中的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆