如何使用RegexKitLite在NSString中转义特殊字符?

时间:2022-10-29 13:29:07

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:

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

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,而不是以反斜杠作为前缀。在第二学期中,我尝试过三次反斜杠,但在XCode中,这些都给了我一个“未知的转义序列”警告。我怎么能在没有RegexKitLite的情况下打印反斜杠呢?

1 个解决方案

#1


7  

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

像往常一样编写表达式,然后用两个反斜杠替换每个反斜杠。因此

\. 

becomes

就变成了

\\. 

and

\\ 

becomes

就变成了

\\\\

#1


7  

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

像往常一样编写表达式,然后用两个反斜杠替换每个反斜杠。因此

\. 

becomes

就变成了

\\. 

and

\\ 

becomes

就变成了

\\\\