Objective-C: Use regular expression to replace string in NSString

在寫一個關於字串處理的小作業時想到的,先留個紀錄。

NSString * strPNum2 = @"(886)02-3356873";

NSError *error = NULL;
// regex 用 \ 做跳脫,但是在 C 裡斜線本身也要跳脫,所以寫成 \\( 來跳脫左括號
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"[\\(\\)-]" options:NSRegularExpressionCaseInsensitive error:&error];

NSString *modifiedString = [regex stringByReplacingMatchesInString: strPNum2 options:0 range: NSMakeRange(0, [strPNum2 length]) withTemplate:@""];

NSLog(@"%@", modifiedString);

電話號碼 (886)02-3356873 會改成 886023356873。


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *