如何在 objective C 中使用正则表达式替换字符串?

How to replace strings using regex in objective C?

我有一个字符串,有时包含如下字符串:@"[id123123|Some Name]" 我要做的就是简单地将它替换为 "Some Name"

例如我有字符串:Some text lalala blabla [id123|Some Name] bla bla bla

我需要得到:一些文字 lalala blabla 一些名字 bla bla bla

问题是怎么办?我的想法告诉我,我可以用 NSRegularExpression

做到这一点

调查stringByReplacingOccurrencesOfString:withString:options:range:options: 允许搜索字符串是正则表达式模式。

不是 Objective C 人,但从 this 之前的 SO post 来看,你可以像这样使用正则表达式:

NSString *regexToReplaceRawLinks = @"\[.+?\|(.+?)\]";   

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSString *string = @"[id123|Some Name]";

NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@""];

这应该与您正在使用的字符串相匹配,并将名称放在一个组中。然后将整个字符串 [id123|Some Name] 替换为 Some Name.

Regex101

(\[[^|]+|([^\]]+]))

描述

\[ matches the character [ literally
[^|]+ match a single character not present in the list below
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
| the literal character |
\| matches the character | literally
1st Capturing group ([^\]]+])
    [^\]]+ match a single character not present in the list below
        Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    \] matches the character ] literally
    ] matches the character ] literally

捕获组 1 中的内容是您要替换为捕获组 2 中的内容。享受吧。