NSPredicate及正規表示式的使用心得 分享

2021-08-26 15:39:19 字數 1950 閱讀 2459

判斷字串首字母是否為字母。

objective-c**

nsstring *regex = @"[a-za-z]+";

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

if ([predicate evaluatewithobject:astring])

nsstring *regex = @"[a-za-z]+";

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

if ([predicate evaluatewithobject:astring])

判斷array中是否包含某一規則的物件,並返回乙個陣列:

nspredicate *filterpredicate = [nspredicate predicatewithformat:@"self contains %@", regex];

獲得乙個陣列中某些物件除外的陣列:

nspredicate *notpredicate = [nspredicate predicatewithformat:@"not (self in %@)", arrayfilter2];且還是要呼叫- (nsarray *)filteredarrayusingpredicate:(nspredicate *)predicate; 方法。

同樣,如果我們想找出某個範圍內的物件,建立如下predicate (這裡可以用到所有的比較操作符): nspredicate *pre = [nspredicate predicatewithformat:@"self.*** < 5"];

並呼叫:- (bool)evaluatewithobject:(id)object;方法。

在這裡囉嗦一句,如果只是在陣列中查詢是否存在物件時用indexofobject,如果不存在則返回為nsnotfound.

字串替換:

objective-c**

nserror* error = null;

nsregularexpression* regex = [nsregularexpression regularexpressionwithpattern:@"(encoding=\")[^\"]+(\")"

options:0

error:&error];

nsstring* sample = @"";

nslog(@"start:%@",sample);

nsstring* result = [regex stringbyreplacingmatchesinstring:sample

options:0

range:nsmakerange(0, sample.length)

withtemplate:@"$1utf-8$2"];

nslog(@"result:%@", result);

nserror* error = null;

nsregularexpression* regex = [nsregularexpression regularexpressionwithpattern:@"(encoding=\")[^\"]+(\")"

options:0

error:&error];

nsstring* sample = @"";

nslog(@"start:%@",sample);

nsstring* result = [regex stringbyreplacingmatchesinstring:sample

options:0

range:nsmakerange(0, sample.length)

withtemplate:@"$1utf-8$2"];

nslog(@"result:%@", result);

from:

NSPredicate 小結 正規表示式

nsstring format nsstring stringwithformat self.nickname like cd searchtext nspredicate perdicate nspredicate predicatewithformat format tableviewshowa...

Lesson 十 正規表示式語法及常用正規表示式

表示匹配字串的開始位置 例外 用在中括號中 時,可以理解為取反,表示不匹配括號中字串 表示匹配字串的結束位置 表示匹配 零次到多次 表示匹配 一次到多次 至少有一次 表示匹配零次或一次 表示匹配單個字元,任意字元 表示為或者,兩項中取一項 小括號表示匹配括號中全部字元 中括號表示匹配括號中乙個字元 ...

正則匹配表

字元描述 轉義字元,在之前,我們在字串也用過這字元,即一些字元具有特殊含義,對其進行轉義使它成為普通字元,而用在普通字元上又表示其有特殊含義 匹配輸入字串的開始位置,如果設定了匹配多行 m 那麼也匹配行的開頭 匹配輸入字串的結束位置。如果設定了匹配多行 m 那麼也匹配行的結束 匹配前面的子表示式零次...