2015-03-31 14 views
0

出於某種原因,我無法使正則表達式適用於多行字符串。它工作正常,網絡上無法在Objective-C中進行正則表達式工作

我有這樣的文字:

First Line //remove leading spaces 
Second Line //nothing to remove 
    Third Line //remove leading spaces 
Fourth Line 
should be 1 line //remove leading spaces and new line next char is not a capital letter 

Fifth line //remove leading spaces, keep new line between the two sentences 

我試圖用這個表達式

^ +|\b\n\b 

它的工作原理幾乎罰款(除非它消除更多的新線路在線正則表達式編輯器,如http://rubular.com/r/u4Ao5oqeBi

但它只是從第一行刪除前導空間 這是我的代碼:

 NSString *myText = @" First Line (remove leading spaces\nSecond Line (nothing to remove\n Third Line (remove leading spaces\n Fourth Line\nshould be 1 line (remove leading spaces and new line next char is not a capital letter\n\n Fifth line (remove leading spaces, keep new line between the two sentences"; 
     NSLog(myText); 

     NSString *resultText = [myText stringByReplacingOccurrencesOfString: @"^ +|\\b\\n\\b" 
                   withString: @"" 
                    options: NSRegularExpressionSearch 
                     range: NSMakeRange(0, myText.length)]; 

     NSLog(resultText); 

回答

1

,因爲你正在使用stringByReplacingOccurrencesOfString與在target論點,而不是輸入字符串正則表達式的字符串代碼不工作。它不接受正則表達式。請參閱Foundation Framework Reference關於此功能的幫助。

您可以使用下面的代碼刪除所有前導空格:

NSError *error = nil; 
NSString *myText = @" First Line (remove leading spaces\nSecond Line (nothing to remove\n Third Line (remove leading spaces\n Fourth Line\nshould be 1 line (remove leading spaces and new line next char is not a capital letter\n\n Fifth line (remove leading spaces, keep new line between the two sentences"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^ +" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error]; 
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:@""]; 
NSLog(@"%@", modifiedString); 

我使用NSRegularExpressionAnchorsMatchLines選項,以使^匹配行的開始,整個字符串並非一開始(見本Regular Expressions Metacharacters表)。 輸出:

First Line (remove leading spaces                                              
Second Line (nothing to remove                                                       
Third Line (remove leading spaces                                                      
Fourth Line                                                            
should be 1 line (remove leading spaces and new line next char is not a capital letter                                         

Fifth line (remove leading spaces, keep new line between the two sentences 
+0

我嘗試類似你所說的東西,但它沒有工作,要麼是因爲我沒有選擇使用NSRegularExpressionAnchorsMatchLines。我修改了你的解決方案,並讓它工作。謝謝! – Tibidabo 2015-03-31 11:16:03

相關問題