Double \\ in regular expression iOS

432 views Asked by At

Does anyone understand what this (([A-Za-z\\s])+)\\? means?
I wonder why it should be "\\s" and "\\" ?

If I entered "\s", Xcode just doesn't understand and if I entered "\?", it just doesn't match the "?".

I have googled a lot, but I did not find a solution. Anyone knows?

3

There are 3 answers

2
Sven On BEST ANSWER

The actual regex is (([A-Za-z\s])+)\?. This matches one or more letters and whitespace characters followed by an question mark. The \ has two different meanings here. In the first instance \s has a fixed meaning and stands for any white space characters. In the second instance the \? means the literal question mark character. The escaping is necessary as the question mark means one or none of the previous otherwise.

You can't type your regex like this in a string literal in C code though. C also does some escaping using the backslash character. For example "\n" is translated to a string containing only a newline character. There are some other escape sequences with special meanings. If the character after the backslash doesn't have a special meaning the backslash is just removed. That means if you want to have a single backspace in your string you have to write two.

So if you wrote your regex string as you wanted you'd get different results as it would be interpreted as (([A-Za-zs])+)? which has a completely different meaning. So when you write a regex in an ObjC (or any other C-based language) string literal you must double all backslash characters.

0
nick On

The \s metacharacter is used to find a whitespace character.

Refer this!

0
Rishabh Singh Bisht On

not sure about ios but same thing happens in java. \ is escape character for java,and c also so when you type \s java reads \ as an escape character.

think of it as if you want to print a \ what will you have to do. you will have to type \\. now first \ will work as escape character for java and second one will be printed.

I think it should be the same concept for ios too.

so if you want \s you type \s, if you want \ you type \\.