1

I have to find number in NSString using NSPredicate. I am using following code.

NSString *test = @"[0-9]";
NSString *testString = @"ab9";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ CONTAINS[c] %@)", test,testString];
BOOL bResult = [predicate evaluateWithObject:testString];

This code is searching for number at only start. I have also tried with @"[0-9]+" and @"[0-9]*" theses expressions but not getting correct result.

Nik
  • 682
  • 1
  • 8
  • 27

3 Answers3

2

Use this

NSCharacterSet  *set= [NSCharacterSet alphanumericCharacterSet];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
    // contains A-Z,a-z, 0-9 
} else {
    // invalid
}

See if it works

amar
  • 4,285
  • 8
  • 40
  • 52
  • Thanks amar for reply i want search for capital letters, small letters ,number in a NSString. So i am going for regular expression. This code will search for digit only. – Nik Jan 10 '13 at 06:54
  • 1
    Thanks amar for reply look like's NSCharacterSet is very useful class. – Nik Jan 10 '13 at 07:00
1

When you say

[predicate testString]

You're actually sending 'testString' message (ie: calling 'testString' method) into predicate object. There is no such thing.

I believe what you should be sending instead is 'evaluateWithObject' message, ie:

BOOL bResult = [predicate evaluateWithObject:testString];

The evaluateWithObject method reference says:

Returns a Boolean value that indicates whether a given object matches the conditions specified by the receiver.

gerrytan
  • 40,313
  • 9
  • 84
  • 99
  • Hi gerrytan thanks for reply it was typing mistake while posting question i am using BOOL bResult = [predicate evaluateWithObject:testString]; in my code but still i am not getting result. – Nik Jan 10 '13 at 06:25
0

Use NSCharacterSet to analyse NSString.

NSCharacterSet  *set= [NSCharacterSet alphanumericCharacterSet];
NSString testString = @"This@9";

BOOL bResult = [testString rangeOfCharacterFromSet:[set invertedSet]].location != NSNotFound;
if(bResult)
    NSLog(@"symbol found");

set = [NSCharacterSet uppercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"upper case latter found");

set = [NSCharacterSet lowercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"lower case latter found");

set = [NSCharacterSet decimalDigitCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"digit found");
Nik
  • 682
  • 1
  • 8
  • 27