iOS Regex: Unknown escape sequence “\|”

前端 未结 2 476
说谎
说谎 2020-12-30 03:26

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:NSReg         


        
2条回答
  •  佛祖请我去吃肉
    2020-12-30 04:25

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

提交回复
热议问题