Zoltan Varadi
Zoltan Varadi

Reputation: 2488

iOS regex with good characters

In my app, i would like to only accept NSStrings that only consist of the following characters:

  • a-z
  • 0-9
  • A-Z
  • space (dec: 32)

What is the NSRegularExpression to recognize that?

Thanks in advance!

Sincerely, Zoli

Upvotes: 1

Views: 3306

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

As per your given details:

only accept NSStrings that only consist of the following characters:

I would like you to try this regex:

^[a-z\\d\\s]*$

It involves ^ (ensure to match from beginning of string) and $ (ensures to match TILL the end of the string)

Check out this snippet:

NSString *sample = @"df$hjkds hfkshf 9397 AZZ";//@"dfhjkds hfkshf 9397 AZZ";
NSError  *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-z\\d\\s]*$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];
NSArray *matches = [regex matchesInString:sample
                                  options:NSMatchingReportProgress
                                    range:NSMakeRange(0, [sample length])];

// Print matches (if any) -- Optional
for (NSTextCheckingResult *match in matches)
    NSLog(@"%@",[sample substringWithRange:match.range]);

// Acknowledge if no matches found -- Optional
if([matches count] == 0)
    NSLog(@"No matches found");

Please note that, the usage of NSRegularExpressionCaseInsensitive in option will not take overhead of matching Uppercase letters (A-Z).

Hope it helps!

Upvotes: 1

Nishant Tyagi
Nishant Tyagi

Reputation: 9913

You can use this :

-(BOOL) NSStringIsValid:(NSString *)checkString
{
   NSString *stricterFilterString = @"[A-Z0-9a-z ]*";

   NSPredicate *stringTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
   return [stringTest evaluateWithObject:checkString];
}

It will return YES if it is valid else NO.

Hope it helps you.

Upvotes: 3

Mike Weller
Mike Weller

Reputation: 45598

NSRegularExpression *regex =
    [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z0-9 ]*"
                                              options:...
                                                error:...];

If you want at least one character, use + instead of *.

Upvotes: 3

Sulthan
Sulthan

Reputation: 130102

I never worked with regular expressions on iOS but according to the documentation, the following should work

[a-z0-9A-Z ]+

Upvotes: 1

Related Questions