Regex for a string combination

Viewed 33
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;
    }
}

Consider below example String:

a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n
  1. In the above example string, a=fmtp:111 can appear anywhere in the string.

  2. We have to get the string between a=fmtp:111 and the next first appearance of \r\n which is av=1 in our case

  3. Now we have to append ;stereo=1;sprop-stereo=1 to av=1 and append back to the original string.

  4. The final output should be

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

Is it possible to achieve the above chunk of logic with Replace with Regex pattern?

1 Answers

You can use

NSError *error = nil;
NSString *fmtpAudio = @"^a=fmtp:111 .*";
NSString *stereoString = @"$0;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);

Output:

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

See the regex demo.

Details

  • ^ - start of a line (^ starts matching line start positions due to the options:NSRegularExpressionAnchorsMatchLines option)
  • a=fmtp:111 - a literal string
  • .* - any zero or more chars other than line break chars as many as possible.

The $0 in the replacement pattern is the backreference to the whole match value.

Related