iPhone Regex for GUIDs - iphone

I was searching around finding some easy regex for iPhone to validate if a NSString is in a valid Hex format, containing only characters from 0-9 and a-f. The same for GUID's. Or is there already a function built in to check if a GUID is valid?
I only found some posts about creating GUIDs. This SO answer is creating GUID's in the format I'm using them.
Sample GUID
ADD2B9F7-A699-4EF3-9A70-130B92154B11

To simplify Zaph's correct answer, just add this method to a category on NSString:
-(BOOL) isGuid {
NSString *regexString = #"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}";
NSRange guidValidationRange = [self rangeOfString:regexString options:NSRegularExpressionSearch];
return (guidValidationRange.location == 0 && guidValidationRange.length == self.length);
}

One way is to use NSCharacterSet:
NSString *testCharacters = #"ABCDEFabcdef0123456789-";
NSCharacterSet *testCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:testCharacters] invertedSet];
NSString *testString1 = #"ADD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range1 = [testString1 rangeOfCharacterFromSet:testCharacterSet];
NSLog(#"testString1: %#", (range1.location == NSNotFound) ? #"Good" : #"Bad");
NSString *testString2 = #"zDD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range2 = [testString2 rangeOfCharacterFromSet:testCharacterSet];
NSLog(#"testString2: %#", (range2.location == NSNotFound) ? #"Good" : #"Bad");
NSLog output:
testString1: Good
testString2: Bad
or using REs:
NSString *reString = #"[a-fA-F0-9-]+";
NSString *testString1 = #"ADD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range1 = [testString1 rangeOfString:reString options:NSRegularExpressionSearch];
NSLog(#"testString1: %#", (range1.location != NSNotFound && range1.length == testString1.length) ? #"Good" : #"Bad");
NSString *testString2 = #"zDD2B9F7-A699-4EF3-9A70-130B92154B11";
NSRange range2 = [testString2 rangeOfString:reString options:NSRegularExpressionSearch];
NSLog(#"testString2: %#", (range1.location != NSNotFound && range2.length == testString2.length) ? #"Good" : #"Bad");
For a more rigorous GUID match:
NSString *reString = #"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}";

Related

NSPredicate search for number in NSString

I have to find number in NSString using NSPredicate. I am using following code.
NSString *test = #"[0-9]";
NSString *testString = #"ab9";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(%# CONTAINS[c] %#)", test,testString];
BOOL bResult = [predicate evaluateWithObject:testString];
This code is searching for number at only start. I have also tried with #"[0-9]+" and #"[0-9]*" theses expressions but not getting correct result.
Use this
NSCharacterSet *set= [NSCharacterSet alphanumericCharacterSet];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
// contains A-Z,a-z, 0-9
} else {
// invalid
}
See if it works
When you say
[predicate testString]
You're actually sending 'testString' message (ie: calling 'testString' method) into predicate object. There is no such thing.
I believe what you should be sending instead is 'evaluateWithObject' message, ie:
BOOL bResult = [predicate evaluateWithObject:testString];
The evaluateWithObject method reference says:
Returns a Boolean value that indicates whether a given object matches
the conditions specified by the receiver.
Use NSCharacterSet to analyse NSString.
NSCharacterSet *set= [NSCharacterSet alphanumericCharacterSet];
NSString testString = #"This#9";
BOOL bResult = [testString rangeOfCharacterFromSet:[set invertedSet]].location != NSNotFound;
if(bResult)
NSLog(#"symbol found");
set = [NSCharacterSet uppercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
NSLog(#"upper case latter found");
set = [NSCharacterSet lowercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
NSLog(#"lower case latter found");
set = [NSCharacterSet decimalDigitCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
NSLog(#"digit found");

Find the index of a character in a string

I have a string NSString *Original=#"88) 12-sep-2012"; or Original=#"8) blablabla";
I want to print only the characters before the ")" so how to find the index of the character ")". or how could i do it?
Thanks in advance.
To print the characters before the first right paren, you can do this:
NSString *str = [[yourString componentsSeparatedByString:#")"] objectAtIndex:0];
NSLog(#"%#", str);
// If you need the character index:
NSUInteger index = str.length;
U can find index of the character ")" like this:
NSString *Original=#"88) 12-sep-2012";
NSRange range = [Original rangeOfString:#")"];
if(range.location != NSNotFound)
{
NSString *result = [Original substringWithRange:NSMakeRange(0, range.location)];
}
You can use the following code to see the characters before ")"
// this would split the string into values which would be stored in an array
NSArray *splitStringArray = [yourString componentsSeparatedByString:#")"];
// this would display the characters before the character ")"
NSLog(#"%#", [splitStringArray objectAtIndex:0]);
NSUInteger index = [Original rangeOfString:#")"];
NSString *result = [Original substringWithRange:NSMakeRange(0, index)];
try the below code to get the index of a particular character in a string:-
NSString *string = #"88) 12-sep-2012";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#")"];
NSRange range = [string rangeOfCharacterFromSet:charSet];
if (range.location == NSNotFound)
{
// ... oops
}
else {
NSLog(#"---%d", range.location);
// range.location is the index of character )
}
and to get the string before the ) character use this:-
NSString *str = [[string componentsSeparatedByString:#")"] objectAtIndex:0];
Another soluation:
NSString *Original=#"88) 12-sep-2012";
NSRange range = [Original rangeOfString:#")"];
NSString *result = Original;
if (range.location != NSNotFound)
{
result = [Original substringToIndex:range.location];
}
NSLog(#"Result: %#", result);

IOS : NSString retrieving a substring from a string

Hey I am looking for a way to extract a string from another string. It could be any length and be in any part of the string so the usual methods don't work.
For example
http://bla.com/bla?id=%1234%&something=%888%
What I want to extract is from id=% to the next %.
Any idea's?
Use the rangeOfString method:
NSRange range = [string rangeOfString:#"id=%"];
if (range.location != NSNotFound)
{
//range.location is start of substring
//range.length is length of substring
}
You can then chop up the string using the substringWithRange:, substringFromIndex: and substringToIndex: methods to get the bits you want. Here's a solution to your specific problem:
NSString *param = nil;
NSRange start = [string rangeOfString:#"id=%"];
if (start.location != NSNotFound)
{
param = [string substringFromIndex:start.location + start.length];
NSRange end = [param rangeOfString:#"%"];
if (end.location != NSNotFound)
{
param = [param substringToIndex:end.location];
}
}
//param now contains your value (or nil if not found)
Alternatively, here's a general solution for extracting query parameters from a URL, which may be more useful if you need to do this several times:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
if ([parts count] > 1)
{
NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
result[key] = value;
}
}
return result;
}
This doesn't strip the % characters from the values, but you can do that either with
NSString *value = [[value substringToIndex:[value length] - 1] substringFromIndex:1];
Or with something like
NSString *value = [value stringByReplacingOccurencesOfString:#"%" withString:#""];
UPDATE: As of iOS 8+ theres a built-in class called NSURLComponents that can automatically parse query parameters for you (NSURLComponents is available on iOS 7+, but the query parameter parsing feature isn't).
Try this
NSArray* foo = [#"10/04/2011" componentsSeparatedByString: #"/"];
NSString* day = [foo objectAtIndex: 0];

Getting the last 2 directories of a file path

I have a file path of, for example /Users/Documents/New York/SoHo/abc.doc. Now I need to just retrieve /SoHo/abc.doc from this path.
I have gone through the following:
stringByDeletingPathExtension -> used to delete the extension from the path.
stringByDeletingLastPathComponent -> to delete the last part in the part.
However I didn't find any method to delete the first part and keep the last two parts of a path.
NSString has loads of path handling methods which it would be a shame not to use...
NSString* filePath = // something
NSArray* pathComponents = [filePath pathComponents];
if ([pathComponents count] > 2) {
NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
}
I've written function special for you:
- (NSString *)directoryAndFilePath:(NSString *)fullPath
{
NSString *path = #"";
NSLog(#"%#", fullPath);
NSRange range = [fullPath rangeOfString:#"/" options:NSBackwardsSearch];
if (range.location == NSNotFound) return fullPath;
range = NSMakeRange(0, range.location);
NSRange secondRange = [fullPath rangeOfString:#"/" options:NSBackwardsSearch range:range];
if (secondRange.location == NSNotFound) return fullPath;
secondRange = NSMakeRange(secondRange.location, [fullPath length] - secondRange.location);
path = [fullPath substringWithRange:secondRange];
return path;
}
Just call:
[self directoryAndFilePath:#"/Users/Documents/New York/SoHo/abc.doc"];
Divide the string into components by sending it a pathComponents message.
Remove all but the last two objects from the resulting array.
Join the two path components together into a single string with +pathWithComponents:
Why not search for the '/' characters and determine the paths that way?
NSString* theLastTwoComponentOfPath;
NSString* filePath = //GET Path;
NSArray* pathComponents = [filePath pathComponents];
int last= [pathComponents count] -1;
for(int i=0 ; i< [pathComponents count];i++){
if(i == (last -1)){
theLastTwoComponentOfPath = [pathComponents objectAtIndex:i];
}
if(i == last){
theTemplateName = [NSString stringWithFormat:#"\\%#\\%#", theLastTwoComponentOfPath,[pathComponents objectAtIndex:i] ];
}
}
NSlog (#"The last Two Components=%#", theLastTwoComponentOfPath);

How to check if a string contains an URL

i have text message and I want to check whether it is containing text "http" or URL exists in that.
How will I check it?
NSString *string = #"xxx http://someaddress.com";
NSString *substring = #"http:";
Case sensitive example:
NSRange textRange = [string rangeOfString:substring];
if(textRange.location != NSNotFound){
//Does contain the substring
}else{
//Does not contain the substring
}
Case insensitive example:
NSRange textRange = [[string lowercaseString] rangeOfString:[substring lowercaseString]];
if(textRange.location != NSNotFound){
//Does contain the substring
}else{
//Does not contain the substring
}
#Cyprian offers a good option.
You could also consider using a NSRegularExpression which would give you far more flexibility assuming that's what you need, e.g. if you wanted to match http:// and https://.
Url usually has http or https in it
You can use your custom method containsString to check for those strings.
- (BOOL)containsString:(NSString *)string {
return [self containsString:string caseSensitive:NO];
}
- (BOOL)containsString:(NSString*)string caseSensitive:(BOOL)caseSensitive {
BOOL contains = NO;
if (![NSString isNilOrEmpty:self] && ![NSString isNilOrEmpty:string]) {
NSRange range;
if (!caseSensitive) {
range = [self rangeOfString:string options:NSCaseInsensitiveSearch];
} else {
range = [self rangeOfString:string];
}
contains = (range.location != NSNotFound);
}
return contains;
}
Example :
[yourString containsString:#"http"]
[yourString containsString:#"https"]