如何使用 RegexKitLite 转义 NSString 中的特殊字符?
我正在构建一个使用用户输入的字符串的正则表达式,但该字符串可能包含特殊字符,例如 . \ 或 * ,我希望将它们视为文字,而不是通过正则表达式中的特殊含义进行解释。我已经尝试过:
NSString *word = [input stringByReplacingOccurrencesOfRegex:@"(\\P{L})" withString:@"\\$1"];
但非字母字符被转换为“$1”,而不是带有反斜杠前缀。我在第二个术语中尝试了一个和三个反斜杠,但这些反斜杠在 XCode 中给了我一个“未知转义序列”警告。如何打印反斜杠而不让 RegexKitLite 认为我正在转义美元符号?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像平常一样编写表达式,然后将每个反斜杠替换为两个。因此
成为
并
成为
Write the expression as you normally would and then replace each single backslash with two. Thus
becomes
and
becomes