Regex Repeatead Consecutive Characters IOS - ios

I'm trying to valide an iOS textfield with a regex for no repeated consecutive characteres
eg. txt12344 -> should fail
this is my code
NSString *regexConsecutive = #"(.)\1{1,}";
NSPredicate *passConsecutivePredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regexConsecutive];
if ([passConsecutivePredicate evaluateWithObject:self.txtPassword.text]){
errorMessage = #"No repeated consecutive characters allowed !";
}
but I'm not sure if self matches it's the right way to achieve this.
Thanks a lot !

Related

Validate a string using regex

I want to validate a string to check if it is alphanumeric and contains "-" and "." with the alphanumeric characters. So I have done something like this to form the regex pattern
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[a-zA-Z0-9\\.\\-]"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSPredicate *regexTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL valid = [regexTest evaluateWithObject:URL_Query];
App crashes stating that the regex pattern cannot be formed . Can anyone give me a quickfix to what am i doing wrong? Thanks in advance.
You must pass a variable of type NSString to the NSPredicate SELF MATCHES:
NSString * URL_Query = #"PAS.S.1-23-";
NSString * regex = #"[a-zA-Z0-9.-]+";
NSPredicate *regexTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL valid = [regexTest evaluateWithObject:URL_Query];
See the Objective C demo
Note that you need no anchors with the SELF MATCHES (the regex is anchored by default) and you need to add + to match one or more allows symbols, or * to match 0+ (to also allow an empty string).
You do not need to escape the hyphen at the start/end of the character class, and the dot inside a character class is treated as a literal dot char.
Also, since both the lower- and uppercase ASCII letter ranges are present in the pattern, you need not pass any case insensitive flags to the regex.

NSPredicate - Return inexact matches

In my app I allow users to search for vehicles by make/model using a textfield keyword search. Here is my predicate:
if (self.keywordSearch.text.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fields.make CONTAINS[cd] %# OR fields.model CONTAINS[cd] %#", self.keywordSearch.text, self.keywordSearch.text];
self.vehicleArray = [[self.vehicleArray filteredArrayUsingPredicate:predicate] mutableCopy];
}
The problem is that if the Vehicle make/model is 'Ford F-150' and the user searches F150, or F 150, the vehicle isn't included in the results. It only returns if they search F-150 or f-150.
Is there a way to make sure these inexact matches are returning?
I suggest using regular expressions for this. You can either use a regular expression literal inside the NSPredicate format (described here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html ) or you can iterate the array manually and use an NSRegularExpression for comparing the strings.

How to check the validation of edit text for pan card in objective c?

I have to validate the test is a valid pan card with help of some regular expression in iOS app development .can any one help this out.
PAN card validation for swift 4.0
func validatePANCardNumber(_ strPANNumber : String) -> Bool{
let regularExpression = "[A-Z]{5}[0-9]{4}[A-Z]{1}"
let panCardValidation = NSPredicate(format : "SELF MATCHES %#", regularExpression)
return panCardValidation.evaluate(with: strPANNumber)
}
Here is very simple function to validate Pan card number.
- (BOOL) validatePanCardNumber: (NSString *) cardNumber {
NSString *emailRegex = #"^[A-Z]{5}[0-9]{4}[A-Z]$";
NSPredicate *cardTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [cardTest evaluateWithObject:cardNumber];
}
For Calling this method.
NSLog(#"%hhd",[self validatePanCardNumber:#"XXXX1111X"]);
With using this your problem solve.
PAN is a 10 digit alpha numeric number, where the first 5 characters are letters, the next 4 numbers and the last one a letter again. These 10
characters can be divided in five parts as can be seen below. The meaning of each number has been explained further.
First three characters are alphabetic series running from AAA to ZZZ
Fourth character of PAN represents the status of the PAN holder.
• C — Company
• P — Person
• H — HUF(Hindu Undivided Family)
• F — Firm
• A — Association of Persons (AOP)
• T — AOP (Trust)
• B — Body of Individuals (BOI)
• L — Local Authority
• J — Artificial Juridical Person
• G — Government
Fifth character represents first character of the PAN holder’s last name/surname.
Next four characters are sequential number running from 0001 to 9999.
Last character in the PAN is an alphabetic check digit
Here my code.
- (BOOL)validatePancard:(NSString *)candidate
{
NSString *panCardRegex = #"[A-Z]{3}P[A-Z]{1}[0-9]{4}[A-Z]{1}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", panCardRegex]; return [emailTest evaluateWithObject:candidate];
}
You could use this code:
- (BOOL)check:(NSString *)input
{
NSString *pattern = #"^[A-Za-z]{5}[0-9]{4}[A-Za-z]$"
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NULL error:&error];
NSArray *matches = [regex matchesInString:input options:NSMatchingProgress range:NSMakeRange(0, input.length)];
return matches.length && matches[0].range.location == 0
}

how to compare only selected strings in a text with given input in objective-c

i know that the question sounds wears.I couldn't find a better way to put it so i will take my time to explain the question i m struggling with.
I have an iPhone app that takes input from user.And i got a plist ( i will convert it to a online database soon) What i currently do is this. I compare my input string with ingredients part of items in my plist.
This is the plist format
<array>
<dict>
<key>category</key>
<string>desert</string>
<key>numberOfPerson</key>
<string>3</string>
<key>recipeImage</key>
<string>asd.jpg</string>
<key>time</key>
<string>15</string>
<key>recipeName</key>
<string>Puding</string>
<key>recipeDetail</key>
i compare the input with recipeIngredients.But what my codes do is not what i need.If the comparison turns true i just list every item from my plist that contain the input ingredients.I can filter through selected recipes but what i want is this: Unless there is a full match up with input and ingredients i do not want to show it.
The problem is this. I got my recipe ingredients like this format 1 spoon of sugar, 1 spoon of salt, 100g chicken.
The user enter inputs like - salt , sugar. chicken so i can not fully compare it.It will never be the same so i can not show anything.
How can i accomplish this.
i m open for any kind of suggestions.
This is how i compare
results = [arrayOfPlist filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSDictionary *_dataRow = (NSDictionary *)evaluatedObject;
return ([[[_dataRow valueForKey:#"recipeIngredients"] lowercaseString] rangeOfString:[searchText lowercaseString]].location != NSNotFound);
}]];
where searchText is my input.
First of all, you'll never know if there is a typo in user input.
But what you can do is before you compare two strings, you can do a little bit trimming for a given character set.
There is a method in NSString class called :
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
If you want to get rid of . or - characters, you need to specify them in your character set. Than, you can compare two strings.
Using -[NSPredicate predicateWithFormat:] you can do database-esque string comparisons. For instance, you could try
[NSPredicate predicateWithFormat:#"recipeIngredients CONTAINS[cd] %#", searchText]
Check out https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html the section called "String Comparisons"
EDIT: if the user will be searching multiple things at once, like "chicken, noodle," you can be a little more fancy and do:
NSArray *tokens = [[searchText componentsSeparatedByCharactersInSet:NSCharacterSet.alphanumericCharacterSet.invertedSet] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"];
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:#"recipeIngredient CONTAINS[cd] (ANY %#)", tokens]
You should split up the searchText into an array by using -componentsSeparatedByString:#",", and then loop through the array to see if the recipeIngredients contains any of the ingredients in the searchText array. In order to work out if the query contains every single ingredient, you can create an integer inside of the block and increment it everytime you have a match. If the number of matches is equal to the number of ingredients, then you can go from there.
The code below builds up a predicate that boils down to "ingredients contains sugar and ingredients contains chocolate"
NSArray* recipes = #[
#{#"recipeIngredients": #"sugar flour chocolate"},
#{#"recipeIngredients": #"sugar chocolate"},
#{#"recipeIngredients": #"flour chocolate"},
#{#"recipeIngredients": #"chocolate"},
];
NSString* search = #"sugar, chocolate";
// split the ingredients we have into an array of strings separated by ',' or ' '
NSArray* haves = [search componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
// Build a list of recipeIngredients CONTAINS have
NSMutableArray* ands = [NSMutableArray new];
for(NSString* have in haves)
{
if(have.length > 0)
{
[ands addObject:[NSPredicate predicateWithFormat:#"recipeIngredients CONTAINS[cd] %#", have]];
}
}
// String all the haves into a single long ... AND ... AND ... predicate
NSPredicate* predicate = [NSCompoundPredicate andPredicateWithSubpredicates:ands];
// Apply the predicate
NSArray* filtered = [recipes filteredArrayUsingPredicate:predicate];

NSPredicate to match unescaped apostrophes

I'd like to check an NSString (json) if there are any unescaped apostrophes, but the NSPredicate won't find it, even if the regex is correct.
Here's my code:
NSString* regx = #"[^\\\\]'";
NSPredicate* p = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",regx];
if([p evaluateWithObject:json]){
//gotit
...
I know that there are some apostrophes that are not escaped, but NSPredicate just doesn't find it.
Any idea how to solve this problem?
Also if I look at the json I see the apostrophes as \u0027.
"SELF MATCHES …" tries to match the entire string, therefore you have to use the regex
NSString* regx = #".*[^\\\\]'.*";
Alternatively:
NSString* regx = #"[^\\\\]'";
NSRange r = [json rangeOfString:regx options:NSRegularExpressionSearch];
if (r.location != NSNotfound) {
…
}
But the question remains why this is necessary. NSJSONSerialization should handle
all escaping and quoting correctly.
This is the regex which works for me:
.*[^\\\\]\\\\u0027.*

Resources