質問

Alright, I'm trying to write some code that removes words that contain an apostrophe from an NSString. To do this, I've decided to use regular expressions, and I wrote one, that I tested using this website: http://rubular.com/r/YTV90BcgoQ

Here, the expression is: \S*'+\S

As shown on the website, the words containing an apostrophe are matched. But for some reason, in the application I'm writing, using this code:

    sourceString = [sourceString stringByReplacingOccurrencesOfRegex:@"\S*'+\S" withString:@""];

Doesn't return any positive result. By NSLogging the 'sourceString', I notice that words like 'Don't' and 'Doesn't' are still present in the output.

It doesn't seem like my expression is the problem, but maybe RegexKitLite doesn't accept certain types of expressions? If someone knows what's going on here, please enlighten me !

役に立ちましたか?

解決

Literal NSStrings use \ as an escape character so that you can put things like newlines \n into them. Regexes also use backslashes as an escape character for character classes like \S. When your literal string gets run through the compiler, the backslashes are treated as escape characters, and don't make it to the regex pattern.

Therefore, you need to escape the backslashes themselves in your literal NSString, in order to end up with backslashes in the string that is used as the pattern: @"\\S*'+\\S".

You should have seen a compiler warning about "Unknown escape sequence" -- don't ignore those warnings!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top