Ios 字符串组合的正则表达式
考虑以下示例字符串:Ios 字符串组合的正则表达式,ios,objective-c,regex,Ios,Objective C,Regex,考虑以下示例字符串: NSString *fmtpAudio = @"a=fmtp:111 "; NSString *stereoString = @";stereo=1;sprop-stereo=1"; NSArray *componentArray = [localSdpMutableStr componentsSeparatedByString:fmtpAudio]; if (componentArray.count >= 2) { N
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:111
可以出现在字符串中的任何位置
a=fmtp:111
和\r\n
的下一次首次出现之间的字符串,在我们的例子中,它是av=1
;立体声=1;sprop stereo=1
到av=1
并追加回原始字符串
NSError*error=nil;
NSString*fmtpAudio=@“^a=fmtp:111.*”;
NSString*立体声字符串=@“$0;立体声=1;存储立体声=1”;
NSString*myText=@“a=fmtp:93 av=2\r\na=fmtp:111 av=1\r\na=fmtp:92 av=2”;
NSRegularExpression*regex=[NSRegularExpression regular expression with pattern:fmtpAudio选项:NSRegularExpression anchorsmatchlines错误:&error];
NSString*modifiedString=[regex StringByReplacingMatcheInstalling:myText选项:0范围:NSMakerRange(0,[myText长度])带模板:立体字符串];
NSLog(@“%@”,modifiedString);
输出:
a=fmtp:93 av=2
a=fmtp:111 av=1;立体声=1;sprop立体声=1
a=fmtp:92 av=2
看
细节
-行的开始(^
由于^
选项,开始匹配行的开始位置)选项:NSRegularExpressionAnchorsMatchLines
-文本字符串a=fmtp:111
-尽可能多的零个或多个字符(断线字符除外)*
替换模式中的
$0
是对整个匹配值的反向引用。能否请您用简单的英语解释一下您试图实现的目标?@WiktorStribiżew已按照您的建议添加。请您现在检查一下。\r\n
是否只是CRLF结尾(即两个字符)?还是文字(即四个字符)?这个示例字符串真的是NSString
?是的。它们是CRLF结尾@WiktorStribiż,像一个符咒一样工作。投票并接受答案。
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n