Check that string contains a character from set of characters - ios

I need to check the complexity of a password. One of the conditions is that the password must contain at least one number. I've tried the following approach but it does not give me expected results and I don't know what's wrong.
NSString *regexpNumbers = #"[0-9]+";
NSPredicate *predicateNumbers = [NSPredicate predicateWithFormat:#"SELF CONTAINS %#", regexpNumbers];
result &= [predicateNumbers evaluateWithObject:password];
evaluateWithObject: method returns NO even if the password contains some number.

Using rangeOfCharacterFromSet:
You can create your own character set like the way:
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
s = [s invertedSet];
NSString *string = #"String to find";
NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
NSLog(#"the string contains illegal characters");
} else {
NSLog(#"Found!!!");
}
Using NSPredicate:
NSString *myRegex = #"[A-Z0-9a-z_]*";
NSPredicate *myTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", myRegex];
NSString *string = #"String to find";
BOOL valid = [myTest evaluateWithObject:string];

When using NSPredicate with regex you need to use MATCHES, not CONTAINS (which is used for direct literal comparison).
Arguably you should't be doing this though. There is an argument that it should be done on the server.
Instead of using regex you could also look to use rangeOfCharacterFromSet: and NSCharacterSet for each of your checks.

Related

Checking if NSMutableArray of names has prefix of multiple characters

I'm trying to split contact names into separate NSMutableArrays and want to include letters with accents amongst these arrays.
if([[contact.givenName lowercaseString] hasPrefix:#"a"]){
[selectedArray addObject:contact];
NSLog(#"%#",contact.givenName);
}
The above works fine for the letter "a", but I wish to include the following:
#"a",#"á",#"â",#"ã",#"ä"
What is the correct way to do this?
Thanks
As Larme suggested you need to use NSDiacriticInsensitiveSearch like this.
if ([contact.givenName length] >= 1) {
NSString *nameFirstLetter = [contact.givenName substringToIndex:1];
NSStringCompareOptions options = NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch;
if([nameFirstLetter compare:#"a" options:options] == NSOrderedSame){
[selectedArray addObject:contact];
NSLog(#"%#",contact.givenName);
}
}
You can filter the array with a predicate, [cd] means case and diacritic insensitive.
Assuming contacts is the array containing the contact instances
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"givenName BEGINSWITH[cd] %#", #"a"];
NSArray *selectedArray = [contacts filteredArrayUsingPredicate:predicate];
The solution is very fast, you even don't need a repeat loop and it handles also the case if the property is empty or nil.
You need to decode your string before check :
NSString *str = #"ä";
NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
if([[newStr lowercaseString] hasPrefix:#"a"]){
NSLog(#"%#",newStr);
}
Use NSDiacriticInsensitiveSearch
NSString *string =#"á";
if ([string rangeOfString:#"a" options:NSDiacriticInsensitiveSearch].location
!= NSNotFound)
{
NSLog(#"found words");
}

How to validate a password which must contain either number or alphabets(or both) as well as special characters?

hi am currently using the following to validate the password but i want to include special characters also. Currently it contains only numbers and alphabets. Please help.
- (BOOL)validatePassword:(NSString *) password{
NSString *ACCEPTABLE_CHARECTERS = #"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
NSString *filtered = [[password componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [password isEqualToString:filtered];
}
You can try this
- (BOOL)validatePassword:(NSString *) password{
if(password.length == 0){
return NO;
}
NSString *regex = #"^(?=(.*\d){2})(?=.*[a-zA-Z])(?=.*[!##$%])[0-9a-zA-Z!##$%]{8,}";
NSPredicate *passwordPredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
return [passwordPredicate evaluateWithObject:password];
}
EXPLANATION
(?=(.*\d){2}) - uses lookahead (?=) and says the password must contain at least 2 digits
(?=.*[a-zA-Z]) - uses lookahead and says the password must contain an alpha
(?=.*[!##$%]) - uses lookahead and says the password must contain 1 or more special characters which are defined
[0-9a-zA-Z!##$%] - dictates the allowed characters
{8,} - says the password must be at least 8 characters long
It might need a little tweaking e.g. specifying exactly which special characters you need but it should do the trick.
-(BOOL)validatePassword:(NSString *) password{
NSString *COMMON_CHARECTERS = #"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
NSString *SPECIAL_CHARECTERS = #"##$%^&*";
NSCharacterSet *cs_common = [NSCharacterSet characterSetWithCharactersInString:COMMON_CHARECTERS];
NSCharacterSet *cs_special = [NSCharacterSet characterSetWithCharactersInString:SPECIAL_CHARECTERS];
NSString *filtere_common = [[password componentsSeparatedByCharactersInSet:cs_common] componentsJoinedByString:#""];
NSString *filtere_special = [[password componentsSeparatedByCharactersInSet:cs_special] componentsJoinedByString:#""];
BOOL valid = (password.length == (filtere_common.length + filtere_special.length));
return valid;
}
You can use regex to identify use of special character. like
^([a-zA-Z+]+[0-9+]+[&#!#+]+)$
You can use character sets as well to validate password:- Check this link

RegEx validation of techmahindra account

I want to validate for textfield of email and wants to find out is it techmahindra email or not. How can I find it . I am attaching my code here.
Could any one suggest changes.
NSString * myString = # "#";
NSArray * myWords = [emailStr componentsSeparatedByString: myString];
NSString * str = [myWords objectAtIndex: 1];
if ([str isEqualToString: # "techmahindra.com"]) {
NSString * emailRegex = # "[A-Z0-9a-z._%+]+#[A-Za-z0-9.]+\\.[A-Za-z]{2,4}";
NSPredicate * emailTest = [NSPredicate predicateWithFormat: # "SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject: emailStr];
} else
return NO;
Given that you have written code to extract the part of the string that follows the # symbol, you don't need regular expressions there. You can simply do a case-insensitive comparison, like this:
if (str != nil && [str compare:#"techmahindra.com" options:NSCaseInsensitiveSearch]) {
return [emailTest evaluateWithObject:emailStr];
}
else
return NO;
You probably should also trim whitespace as part of your email validation code as this check will fail if there is a trailing space for example.

Regular Expression for URL matching not working in iOS

I found a PHP regular expression to detect a Web URL:
$url_pattern = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:#\-_=#]+\.([a-zA-Z0-9\.\/\?\:#\-_=#])*/';
This regular expression can match URLs like those below:
http://www.google.com
www.google.com
google.com
Now, I am trying to use it in Objective-C as:
NSString * expression = #"/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:#\-_=#]+\.([a-zA-Z0-9\.\/\?\:#\-_=#])*/";
NSRegularExpression * regularExp = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:nil];
NSInteger numberOfMatches = [regularExp numberOfMatchesInString:#"www.google.com" options:0 range:NSMakeRange(0, URLString.length)];
if (numberOfMatches >= 1)
{
return #"webURL";
}
else
{
return #"searchEngine";
}
It is not detecting any kind of URL. I tested it at regexr.com.
You should bear in mind that the PHP regex is usually used within delimiters that should be removed when using such regex patterns in Objective C. Also, we do not have to escape every non-word character inside a character class (only a hyphen), but outside a character class, you must double-escape special characters.
So, use
NSString *pattern = #"(?:(?:http|https)://)?[a-zA-Z0-9./?:#\\-_=#]+\\.([a-zA-Z0-9./?:#\\-_=#])*";
Or, you can even contract to
NSString *pattern = #"(?:(?:http|https)://)?[\\w./?:#=#-]+\\.([\\w./?:#=#-])*";
See the hyphen at the end of character class does not need escaping.
See CodingGround demo
check this one :
NSString urlRegEx = #"(http|https)://((\w)|([0-9])|([-|_]))+(\.|/)+";
I am using this one in my app
Please Try following code for validate URL
- (BOOL) validateUrl: (NSString *) stringURL {
NSString *urlRegEx =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:stringURL];
}

check if one big string contains another string using NSPredicate or regular expression

NSString *string = #"A long term stackoverflow.html";
NSString *expression = #"stack(.*).html";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", expression];
BOOL match = [predicate evaluateWithObject:string]
if(match){
NSLog(#"found");
} else {
NSLog(#"not found");
}
how can i search if expression is present in string or not. above code is working for one word. but not if i put some more words in string to be searched
If you would like to check a string with a regex value then you should use NSRegularExpression not NSPredicate.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"stack(.*).html" options:0 error:nil];
Then you can use the functions to find matches...
NSString *string = #"stackoverflow.html";
NSUInteger matchCount = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSLog(#"Number of matches = %d", matchCount);
Note: I'm terrible at creating regex patterns so I have just used your pattern and example. I have no idea if the pattern will actually find a match in this string but if there is a match it will work.
NSPredicate only matches complete strings, so you should change your pattern to cover the whole string:
NSString *expression = #".*stack(.*).html.*";
However, your original pattern will also match something like "stack my files high as html", so you may want to read up on your regex patterns.
Improve your question , but see below answer for your question
NSString *string = #"This is the main stringsss which needs to be searched for some text the texts can be any big. let us see";
if ([string rangeOfString:#"."].location == NSNotFound) {
NSLog(#"string does not contains");
} else {
NSLog(#"string contains !");
}

Resources