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

时间:2022-09-02 09:49:23

In PHP I'd do something like this:

在PHP中,我会做这样的事情:

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

But in Objective-C, I tried this:

但在Objective-C中,我试过这个:

    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?

但它最终只是删除下一句的第一个字母(例如“结束。克里斯” - >“结束.hris”)。为什么是这样?

1 个解决方案

#1


3  

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

使用$ 1,$ 2等代替\ 1,\ 2等进行反向引用。

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

请参阅NSRegularExpression的文档。查看“模板匹配格式”部分。

#1


3  

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

使用$ 1,$ 2等代替\ 1,\ 2等进行反向引用。

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

请参阅NSRegularExpression的文档。查看“模板匹配格式”部分。