简体   繁体   中英

Escaping backslash in regex in NSString

I have a regex to match _text_ but to not match \\_text\\_ as [^\\\\_]_(.)*[^\\\\_]_ This seems to work on the online RegExr parsing tool. My attempt to make it as an NSString is not working. I have this: @"[^\\\\\\\\_]_(.)*[^\\\\\\\\_]_"

Any pointers would be helpful.

The string you provided works for me, but should't the negated set at the start of the expression have a "*" quantifier?

NSString *goodString = @"_text_";
NSString *badString = @"\\_text\\_";
NSError *error;

NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"[^\\\\_]*_(.)*[^\\\\_]_"
                              options:0
                              error:&error];

NSLog(@"%@ - %lu", goodString, (unsigned long)[regex numberOfMatchesInString:goodString options:0 range:NSMakeRange(0, goodString.length)]);
NSLog(@"%@ - %lu", badString, (unsigned long)[regex numberOfMatchesInString:badString options:0 range:NSMakeRange(0, badString.length)]);

Result:

_text_ - 1
\_text\_ - 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM