2013-04-11 70 views
1

與給定的字符串替換正則表達式的第1組,我有以下的正則表達式如何在目標C

regex = [NSRegularExpression regularExpressionWithPattern:@"(.*)|(.*)" 
                options:NSRegularExpressionCaseInsensitive 
                error:&error]; 

我想替換字符串的第一組匹配這個表達式,從文本值領域。

例如,如果我有Hi|PeterGoodbye代替我得到Goodbye|Peter

我怎樣才能做到這一點?

回答

7

這是你在找什麼?

NSString *s1 = @"Hi|Peter"; 
NSError *error; 
NSString *pattern = @"(.*)\\|(.*)"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern 
             options:NSRegularExpressionCaseInsensitive 
            error:&error]; 
NSString *s2 = [regex stringByReplacingMatchesInString:s1 
          options:0 
         range:NSMakeRange(0, [s1 length]) 
         withTemplate:@"Goodbye|$2"]; 
NSLog(@"%@", s2); 
// Output: Goodbye|Peter 

$2在替換模板中是指第二個捕獲組。請注意,您有 可以跳過「|」正則表達式中的字符。

+0

我認爲就是這樣。非常感謝。我會試試看,並回來標記你的答案是正確的。 – 2013-04-11 13:44:51

+0

我對模板進行了修改以適應文本字段'withTemplate:[NSString stringWithFormat:@「$ 1 |%@」,textField.text]];' – 2013-04-11 13:57:20

+0

@TiagoVeloso的值:現在您保留第一個捕獲組並更換第二組? – 2013-04-11 15:01:07