RegexKitLite 未正确匹配 NSString

发布于 2024-12-14 03:38:41 字数 565 浏览 1 评论 0原文

好吧,我正在尝试编写一些代码,从 NSString 中删除包含撇号的单词。为此,我决定使用正则表达式,并编写了一个正则表达式,并使用以下网站进行了测试: http: //rubular.com/r/YTV90BcgoQ

这里的表达式为:\S*'+\S

如网站所示,包含撇号的单词是 匹配。但由于某种原因,在我正在编写的应用程序中,使用以下代码:

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

不返回任何积极结果。通过 NSLogging 'sourceString',我注意到像 'Don't' 和 'Doesn't' 这样的词仍然出现在输出中。

看来我的表达式不是问题,但也许 RegexKitLite 不接受某些类型的表达式?如果有人知道这里发生了什么,请赐教!

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 !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百合的盛世恋 2024-12-21 03:38:41

文字 NSString 使用 \ 作为转义字符,以便您可以将换行符 \n 等内容放入其中。正则表达式还使用反斜杠作为 \S 等字符类的转义字符。当您的文字字符串通过编译器运行时,反斜杠将被视为转义字符,并且不会进入正则表达式模式。

因此,您需要在文字 NSString 中对反斜杠本身进行转义,以便最终在用作模式的字符串中使用反斜杠:@"\\S*'+\ \S"

您应该已经看到有关“未知转义序列”的编译器警告 - 不要忽略这些警告!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文