2013-05-09 43 views
1

我有包含[[和]]和{{和}}出現次數的字符串。在下面的代碼中哪個正則表達式可以工作,以保證[] {}的單次出現保持不變?目標C:正則表達式匹配{{和}}和[[和]]

NSString* initialString = @"[[hi]] {{this}} {is} [a] {{string}}"; 
NSString* regex = @""; // Which regex would work 
NSString* finalString = [match stringByReplacingOccurrencesOfRegex:regex withString:@""]; 

預期輸出:

。在這個{}是[A]字符串

+0

? – Balu 2013-05-09 06:38:54

+0

對不起...更新了帖子...我想要所有的{..}和[..]完好無損,而所有[[..]]和{{..}}被剝離 – Amarsh 2013-05-09 06:50:08

回答

0

那麼最明顯的一點是:

@"\\{\\{|\\}\\}|\\[\\[|\\]\\]" 

字面只是指定匹配{{}}[[]],各種因爲{,},[和]是通常指定正則表達式的語法的所有部分,因此斜槓shes本身需要在字符串文字中轉義。

因此,例如,

NSRegularExpression *expression = [NSRegularExpression 
     regularExpressionWithPattern:@"\\{\\{|\\}\\}|\\[\\[|\\]\\]" 
     options:0 
     error:nil]; 

NSString *initialString = @"[[hi]] {{this}} {is} [a] {{string}}"; 
NSString *finalString = 
    [expression 
     stringByReplacingMatchesInString:initialString 
     options:0 
     range:NSMakeRange(0, [initialString length]) 
     withTemplate:@""]; 

NSLog(@"final string: %@", finalString); 

輸出:

2013-05-09 00:15:57.699 Untitled[1064:707] final string: hi this {is} [a] string 
你想從字符串中刪除[[]] {{}}所有這些charecters
+0

您可以使用Objective-使用C++ 11的「原始字符串」功能來擺脫雙反斜槓:'pattern = @R「(\ {\ {| \} \} | \ [\ [| \] \])」'。 – 2013-05-09 14:03:43

0

嘗試這樣可能it'l幫助你。

NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[[]]{{}}"];// declare set of unwanted charecters here. 
NSString* initialString = @"[[hi]] {{this}} {is} [a] {{string}}"; 

initialString = [[initialString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; 

O/P: -

hi this is a string