I'm working on a small iphone project and i would need to check if the userName entered only contains alphanumerical characters? (A-Z, a-z, 0-9). How would i go about checking it?
views:
2170answers:
4
+2
A:
You can use this regular expression library for ObjectiveC. Use the following regex to match:
^[a-zA-Z0-9]*$
Soviut
2009-11-04 04:04:13
Not wrong, but really overkill.
Chuck
2009-11-04 08:11:27
+6
A:
If you don't want to bring in a regex library for this one task...
NSString *str = @"aA09";
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
Jason Harwig
2009-11-04 04:29:26
thz alot dude i was thinking something along the same line as you, but just couldn't figure out how
DrkZeraga
2009-11-04 06:34:19
+6
A:
This will work:
@implementation NSString (alphaOnly)
- (BOOL) isAlphaNumeric
{
NSCharacterSet *unwantedCharacters =
[[NSCharacterSet alphanumericCharacterSet] invertedSet];
return ([self rangeOfCharacterFromSet:unwantedCharacters].location == NSNotFound) ? YES : NO;
}
@end
NSResponder
2009-11-04 08:02:14
The `? YES : NO` isn't really necessary. The result of a logical comparison is already a boolean value.
Chuck
2009-11-04 08:10:42
I know, I just like to see it so that I don't read it later and think I left something out.
NSResponder
2009-11-04 08:13:38
hey that's nice too man i didn't know u could invert the character set. lol wonder how does that work for other languages like Chinese
DrkZeraga
2009-11-09 04:06:54
Works the same for all character sets. Unicode is well-supported in Cocoa.
NSResponder
2009-11-09 13:01:05
+1
A:
I really like the RegexKit Lite Framework. It uses the ICU regex library, which is already included with OSX and is unicode-safe.
NSString *str = @"testString";
[str isMatchedByRegex:@"^[a-zA-Z0-9]*$"]; // strict ASCII-match
[str isMatchedByRegex:@"^[\p{L}\p{N}]*$"]; // unicode letters and numbers match
Adrian
2009-11-04 16:46:06