Objective regex evaluateWithObject is not working - iphone

When I tried matching the string with the regex '^(34|37)' it does not work even after giving the correct one. Can anyone please point out or guide me to what I am doing wrong?
This is my code:
NSPredicate *myTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", #"^(34|37)"];
if([myTest evaluateWithObject: #"378282246310005"]){
NSLog(#"match");
}

Your regex will not match the given string. That is ^(34|37) does not match 378282246310005. It matches the first two characters, but after that it fails because the string contains more characters, while your regex terminates.
You need to alter your regex to match the rest of the characters, even if you don't want to capture them. Try changing your regext to ^(34|37).*.

Make seprate method for matching regex as bool type. Then it will work.
like this
- (IBAction)tapValidatePhone:(id)sender
{
if(![self validateMobileNo:self.txtPhoneNo.text] )
{
NSLog(#"Mobile No. is not valid");
}
}
-(BOOL) validateMobileNo:(NSString *) paramMobleNo
{
NSString *phoneNoRegex = #"^(34|37)";
NSPredicate *phoneNoTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",phoneNoRegex];
return [phoneNoTest evaluateWithObject:#"3435"];
}
it is not going in else condition.

Why not just use hasPrefix:
if([#"378282246310005" hasPrefix:#"34"] || [#"378282246310005" hasPrefix:#"37"])
{
NSLog(#"found it");
}
EDIT:
Using NSPredicate:
NSPredicate *myTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", #"^3(4|7)\\d+$"];
if([myTest evaluateWithObject: #"378282246310005"])
{
NSLog(#"match");
}
else
{
NSLog(#"notmatch");
}
Using NSRegularExpression:
NSError *error = nil;
NSString *testStr = #"348282246310005";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^3(4|7)" options:NSRegularExpressionCaseInsensitive error:&error];
NSInteger matches = [regex numberOfMatchesInString:testStr options:NSMatchingReportCompletion range:NSMakeRange(0, [testStr length])];
if(matches > 0 )//[myTest evaluateWithObject: #"378282246310005"])
{
NSLog(#"match");
}
else
{
NSLog(#"notmatch");
}
BTW: (34|37) does not look 34 or 37 instead it seems 347 or 337 to me, since engine will pick 4|3 either 4 or 3.

Related

how to write NSRegularExpression to xx:xx:xx?

i am trying to check if NSString is in specific format. dd:dd:dd. I was thinking of NSRegularExpression. Something like
/^(\d)\d:\d\d:\d\d)$/ ?
Have you tried something like:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^\d{2}:\d{2}:\d{2}$"
options:0
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
(I haven't tested it, because I cannot right now, but it should be working)
I suggest to use RegexKitLite
With this and assuming that in dd:dd:dd 'd' actually stands for a digit from 0-9 it should be fairly easy to implement what you need given the additional comment from Grijesh.
Here's an example copied from the RegexKitLite page:
// finds phone number in format nnn-nnn-nnnn
NSString *regEx = #"{3}-[0-9]{3}-[0-9]{4}";
NSString *match = [textView.text stringByMatching:regEx];
if ([match isEqual:#""] == NO) {
NSLog(#"Phone number is %#", match);
} else {
NSLog(#"Not found.");
}
UPDATE:
NSString *idRegex = #"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]";
NSPredicate *idTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", idRegex];
for (NSString * str in newArrAfterPars) {
if ([idTest evaluateWithObject:str]) {
}
}

Alter reg-ex for email Validation on iphone

I am trying to validate email using reg-ex. here is the code...
+ (BOOL) stringIsValidEmail:(NSString *)checkString;
{
NSString *emailRegEx =
#"(?:[a-zA-Z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
#"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
#"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-"
#"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
#"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
#"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
#"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
return [emailTest evaluateWithObject:checkString];
}
now I don't have much knowledge about regex but this accepts a#a.c as a valid email. But this should not be the case and at least two characters should be required at the end. What paramater do I need to change in this so it returns false. I have hit and tried but that didn't work. Thanks for your help.
Too much symbols, you can try this
- (BOOL) IsValidEmail:(NSString *)checkString {
BOOL sticterFilter = YES;
NSString *stricterFilterString = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSString *laxString = #".+#.+\\.[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = sticterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
Try using this as regex
NSString *emailRegex = #"[A-Z0-9a-z._]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
the {2,4} especially validates that the ending characters should be alphabets and more than two in count

How can i find NSString having atlease one charater in iPhone app?

Am working on Message based iPhone app. I have to pass numbers to Webservice if the k like a-z and A-Z i have alert the user to omit the letters from the numbers. How can i find NSString value having a-z and A-Z letters in it? Anyone please help me. Thanks in advance.
That should be it :)
NSCharacterSet *alphaSet = [NSCharacterSet letterCharacterSet];
BOOL valid = [[yourString stringByTrimmingCharactersInSet:alphaSet] isEqualToString:#""];
It removes all the letters from your string, if there is anything left, then valid is NO.
Hope that helps ! :)
Do this:
NSCharacterSet *alphabetSet = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ"] invertedSet];
if ([yourString rangeOfCharacterFromSet:alphabetSet].location == NSNotFound) {
if(yourString.length >= 1)
{
// has aleast one character
}
}
If you just want to check if there is ANY character in your string use something like this:
if ([yourString length] > 0) {
// nice feature here is, this will also work when yourString is nil! :D
}
---
If you want to do a more complex check you will have to use Regular Expressions. Use NSRegularExpression class like this:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[A-Za-z]+$" options:0] error:NULL];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:yourString
options:0
range:NSMakeRange(0, [string length])];
if (numberOfMatches > 0) {
// yourString does only consist of multiple letters
}
^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively). ^[0-9]+$ matches numbers only.
NSString * regexName = #"[a-zA-Z] * ";
NSString *testString = #"your string";
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",regexName];
if ([predicate evaluateWithObject:testString]) {
NSLog(#"true");
}
else{NSLog"string contains numbers or special characters" ;}
From What I understand you want phone Numbers to be entered
First of all you can set the keypad as UIKeyboardTypePhonePad or UIKeyboardTypeNumberPad for the UITextView you are adding the numbers to.
OR
Pass the text to this function
-(BOOL) checkForPhoneNumber:(NSString *) string
{
NSPredicate *confidenceTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",NUMBER_REGEX];
return [confidenceTest evaluateWithObject:string]?YES:NO;
}
where
#define NUMBER_REGEX #"^[0-9]10?$"

Matching HTML with NSRegularExpression

Basically I'm looking for a good example of matching HTML (also newlines and whitespace) using NSRegularExpression.
I have this PHP code I wrote a while back:
preg_match_all("/<dt>(.+?)<\/dt>\W+<dd>(.+?)<\/dd>/si", $data, $m['deets']);
Now I know this works in PHP but for the life of me I can't translate it to Objective-C. Here was my attempt.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"<dt>(.+?)<\/dt>\W+<dd>(.+?)<\/dd>" options:(NSRegularExpressionCaseInsensitive) error:&error];
return [regex matchesInString:target options:NSCaseInsensitiveSearch range:NSMakeRange(0, [target length])];
My target in this case is a bunch of HTML.
I never used NSRegularExpression, but NSPredicate instead :
NSError *error = NULL;
NSString* pattern = #"/<dt>(.+?)<\/dt>\W+<dd>(.+?)<\/dd>/si";
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pattern];
if ([predicate evaluateWithObject:myTargetString] == YES) {
// Okay
} else {
// Not found
}
Hope this helps.
EDIT :
NSPredicate is cool, be don't work if you want to get the matching range of your target string.
Your code is right, but the problem comes from the regexp expression, you must escape your \ characters and not escape / ones.
#"<dt>(.+?)</dt>\\W+<dd>(.+?)</dd>"
So :
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"<dt>(.+?)</dt>\\W+<dd>(.+?)</dd>" options:(NSRegularExpressionCaseInsensitive) error:&error];
return [regex matchesInString:target options:NSCaseInsensitiveSearch range:NSMakeRange(0, [target length])];

Search is only matching words at the beginning

In one of the code examples from Apple, they give an example of searching:
for (Person *person in personsOfInterest)
{
NSComparisonResult nameResult = [person.name compare:searchText
options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
range:NSMakeRange(0, [searchText length])];
if (nameResult == NSOrderedSame)
{
[self.filteredListContent addObject:person];
}
}
Unfortunately, this search will only match the text at the start. If you search for "John", it will match "John Smith" and "Johnny Rotten" but not "Peach John" or "The John".
Is there any way to change it so it finds the search text anywhere in the name? Thanks.
Try using rangeOfString:options: instead:
for (Person *person in personsOfInterest) {
NSRange r = [person.name rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
if (r.location != NSNotFound)
{
[self.filteredListContent addObject:person];
}
}
Another way you could accomplish this is by using an NSPredicate:
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", searchText];
//the c and d options are for case and diacritic insensitivity
//now you have to do some dancing, because it looks like self.filteredListContent is an NSMutableArray:
self.filteredListContent = [[[personsOfInterest filteredArrayUsingPredicate:namePredicate] mutableCopy] autorelease];
//OR YOU CAN DO THIS:
[self.filteredListContent addObjectsFromArray:[personsOfInterest filteredArrayUsingPredicate:namePredicate]];
-[NSString rangeOfString:options:] and friends are what you want. It returns:
"An NSRange structure giving the location and length in the receiver of the first occurrence of aString, modulo the options in mask. Returns {NSNotFound, 0} if aString is not found or is empty (#"")."