Test If NSString Contains an Email

I am working on an iPhone project and I need to check if the user contains an input in a UITextfield email. More generally, if NSString contains a letter.

I tried this with a giant if loop with rangeofstring:@"A".location == NSNotFound , and then did OR rangeofstring:@"B".location == NSNotFound

etc....

But:

  • He does not work
  • There should be a simple line of code to check if NSString contains letters.

I searched for this for hours ... Maybe someone can answer this question ???

+4
source share
2 answers

Use NSCharacterSet . Note that letterCharacterSet includes all things that are “letters” or “ideographers.” Thus, this includes é and 中, but usually this is what you want. If you need a specific set of letters (for example, English letters), you can create an NSCharacterSet NSCharacterSet with it using characterSetWithCharactersInString:

 if ([string rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location == NSNotFound) 
+12
source

If you want to make sure that the text has a specific letter (instead of a simple letter), use the message rangeOfString: For example, so that the text contains the letter "Q":

 NSString *string = @"poQduu"; if ([string rangeOfString:@"Q"].location != NSNotFound) { DLog (@"Yes, we have a Q at location %i", [string rangeOfString:@"Q"].location ); } 

Like others (Rob Napier), note that if you want to find ANY letter, use the message rangeOfCharacterFromSet:

 if ([string rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound) ... 
+6
source

Source: https://habr.com/ru/post/1383974/


All Articles