简体   繁体   中英

How do I do backreferences correctly in Objective-C with NSRegularExpression?

In PHP I'd do something like this:

在此处输入图片说明

But in Objective-C, I tried this:

    regex = [NSRegularExpression regularExpressionWithPattern:@"\\.([a-zA-Z0-9])" options:NSRegularExpressionCaseInsensitive error:&error];
    result = [regex stringByReplacingMatchesInString:result options:0 range:NSMakeRange(0, [result length]) withTemplate:@". \1"];

But it ends up simply removing the first letter of the next sentence (such as "end. Chris" -> "end. hris"). Why is this?

Use $1 , $2 , etc. instead of \\1 , \\2 , etc. for back references.

See the docs for NSRegularExpression . Look under the "Template Matching Format" section.

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