iOS正则表达式:未知的转义序列“\ |” [英] iOS Regex: Unknown escape sequence "\|"
问题描述
我收到一个奇怪的警告,因此我的正则表达式搜索无效。这是行:
I'm getting a weird warning, and as a result my regex search isn't working. Here's the line:
NSRange r = [HTML rangeOfString:@"\|(.*)\|" options:NSRegularExpressionSearch];
其中 HTML
是我的字符串确定包含上述正则表达式的单个匹配。
Where HTML
is a string that I'm sure contains a single match for the above regex.
警告仅在第一次出现\ |时出现,而不是两者都出现。
The warning is only on the first occurrence of "\|", not on both.
非常感谢任何帮助!
推荐答案
您收到警告,因为 \ |
不是Objective-C(或C或C ++)中的有效转义序列。编译器忽略了这一点而只是使用原始的 |
字符,所以你实际传入的字符串是 @|(。*) |
。
You're getting the warning because \|
is not a valid escape sequence in Objective-C (or C or C++ for that matter). The compiler is ignoring that and just using a raw |
character instead, so the string you're actually passing in is @"|(.*)|"
.
要获得所需的行为,您必须转义源代码中的反斜杠,以便正则表达式引擎看到文字反斜杠并将 |
字符解释为文字而不是替换,例如 @\\ |(。*)\\ |
。
To get the behavior you want, you have to escape the backslash in your source code so that the regex engine sees the literal backslash and interprets the |
character as a literal instead of as alternation, e.g. @"\\|(.*)\\|"
.
这篇关于iOS正则表达式:未知的转义序列“\ |”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!