3

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?

Mike T
  • 1,163
  • 1
  • 11
  • 27

1 Answers1

7

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

\. 

becomes

\\. 

and

\\ 

becomes

\\\\
Matthew Frederick
  • 22,245
  • 10
  • 71
  • 97
  • Thanks Matthew. Four backslashes is what is needed in this case. Don't know why I didn't try it in the first place. – Mike T Dec 05 '10 at 07:45