2

I'm looking to strip the whitespace out of the beginning and end of my string. I'm using the following regular expression.

NSString *pattern = @"(?:^\s+|\s+$)";

This is coming up with an error that \s is not a valid escape character. Replacing this with \\s appears to work but what I'd like to know is why? I thought \s is a whitespace charecter and \\s would give me a literal string of '\s'?

Declan McKenna
  • 4,321
  • 6
  • 54
  • 72

2 Answers2

4

\s (not /s) is the regex escape for a whitespace character.

But in an NSString literal (and C string literals), you need to escape backslashes with a backslash to prevent the backslash from being used as a character escape sequence.

This is why you need \\s in your NSString. Otherwise the compiler thinks you are trying to use the escape character \s which isn't a valid C/Objective-C escape character (valid example are \n, \t, etc.).

rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

You're right in thinking \s is the space sequence in regular expressions however you have to think about what context you're writing this regex in.

You're writing a regular expression inside of a string which means you need to escape certain character such as \ otherwise you would be able to write \n and it would literally be interpreted as a newline. Example of what it would interpret the string @"{\n}" as:

"{
}"

To sum this up, you just need to escape \ so that it doesn't try to escape s (which \s doesn't mean anything in the context of a string as xcode is correctly reporting to you).

tl;dr escape \ in strings so they get interpreted properly in the regular expressions.

Another answer that talks about escape sequences

Community
  • 1
  • 1
d0nut
  • 2,835
  • 1
  • 18
  • 23