iOS Regex: Unknown escape sequence “\|”

帅比萌擦擦* 提交于 2019-11-29 06:15:51

问题


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];

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.

Any help is much appreciated!


回答1:


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. @"\\|(.*)\\|".




回答2:


Just to add up, if you are dealing with special character sequences in unicode format, you can use something like this:

const unichar specialCharSequence='some special character';
if(specialCharSequence==L'\uxxxx')
{
   //handle the occurence of this special character
}


来源:https://stackoverflow.com/questions/11442101/ios-regex-unknown-escape-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!