天天看點

iOS中系統自帶正規表達式的應用

//組裝一個字元串,把裡面的網址解析出來

nsstring *urlstring = @"sfdshttp://www.baidu.com";

nserror *error;

//http+:[^\\s]* 這是檢測網址的正規表達式

nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@"http+:[^\\s]*" options:0 error:&error];

if (regex != nil) {

nstextcheckingresult *firstmatch = [regex firstmatchinstring:urlstring options:0 range:nsmakerange(0, [urlstring length])];

if (firstmatch) {

nsrange resultrange = [firstmatch rangeatindex:0];

//從urlstring中截取資料

nsstring *result = [urlstring substringwithrange:resultrange];

nslog(@"%@",result);

}

  輸出結果為:

  [1302:403] http://www.baidu.com

  可見通過ios自帶的正規表達式的類可以達到過濾和篩選字元串的功能。

  還有其他兩種正規表達式的用法:

  1.利用nspredicate(謂詞)比對

  例如比對有效郵箱:

  nsstring *email = @“[email protected]”;

  nsstring *regex = @"[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}";

  nspredicate *predicate = [nspredicate predicatewithformat:@"self matches %@", regex];

  bool isvalid = [predicate evaluatewithobject:email];

  謂詞比對比較靈活,但是需要有謂詞的相關知識。

  2.利用rangeofstring:option:直接查找

  nsstring *searchtext = @"// do any additional setup after loading the view, typically from a nib.";

  nsrange range = [searchtext rangeofstring:@"(?:[^,])*\\." options:nsregularexpressionsearch];

  if (range.location != nsnotfound) {

  nslog(@"%@", [searchtext substringwithrange:range]);

  }

  options中設定nsregularexpressionsearch就是表示利用正規表達式比對,會傳回第一個比對結果的位置。

  小結:

最新内容請見作者的github頁:http://qaseven.github.io/

繼續閱讀