字符串组合的正则表达式

Regex for a string combination

NSString *fmtpAudio = @"a=fmtp:111 ";
NSString *stereoString = @";stereo=1;sprop-stereo=1";
NSArray *componentArray = [localSdpMutableStr componentsSeparatedByString:fmtpAudio];
if (componentArray.count >= 2) {
    NSString *component = [componentArray objectAtIndex: 1];
    NSArray *fmtpArray = [component componentsSeparatedByString:@"\r\n"];
    if (fmtpArray.count > 1) {
        NSString *fmtp = [fmtpArray firstObject];
        NSString *fmtpAudioOld = [NSString stringWithFormat:@"%@%@", fmtpAudio, fmtp];
        fmtpAudio = [NSString stringWithFormat:@"%@%@%@", fmtpAudio, fmtp, stereoString];
        NSString *stereoEnabledSDP = [NSString stringWithString: localSdpMutableStr];
        stereoEnabledSDP = [stereoEnabledSDP stringByReplacingOccurrencesOfString: fmtpAudioOld withString: fmtpAudio];
        localSdpMutableStr.string = stereoEnabledSDP;
    }
}

考虑以下示例字符串:

a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n
  1. 在上面的示例字符串中,a=fmtp:111 可以出现在字符串的任何位置。

  2. 我们必须得到 a=fmtp:111\r\n 的下一个第一次出现之间的字符串,在我们的例子中是 av=1

  3. 现在我们必须将 ;stereo=1;sprop-stereo=1 追加到 av=1 并追加回原始字符串。

  4. 最终输出应该是

    a=fmtp:93 av=2\r\n a=fmtp:111 av=1;立体声=1;sprop-立体声=1\r\n a=fmtp:92 av=2\r\n

是否可以使用 Replace with Regex 模式实现上述逻辑块?

您可以使用

NSError *error = nil;
NSString *fmtpAudio = @"^a=fmtp:111 .*";
NSString *stereoString = @"[=10=];stereo=1;sprop-stereo=1";
NSString *myText = @"a=fmtp:93 av=2\r\na=fmtp:111 av=1\r\na=fmtp:92 av=2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:fmtpAudio options:NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate: stereoString];
NSLog(@"%@", modifiedString);

输出:

a=fmtp:93 av=2
a=fmtp:111 av=1;stereo=1;sprop-stereo=1
a=fmtp:92 av=2

参见regex demo

详情

  • ^ - 行的开始(^ 开始匹配行的开始位置,因为 options:NSRegularExpressionAnchorsMatchLines 选项)
  • a=fmtp:111 - 文字字符串
  • .* - 尽可能多的除换行符之外的任何零个或多个字符。

替换模式中的[=17=]是对整个匹配值的反向引用。