Evaluate/compare NSString with wildcards? - iphone

Hi
I'm trying to evaluate an NSString to see if it fits a certain criteria, which contains wildcards in the form of one or more asterix characters.
Example:
NSString *filePath = #"file://Users/test/Desktop/file.txt";
NSString *matchCriteria = #"file://*/file.*";
I would like to see if filePath matches (fits?) matchCriteria, in this example it does.
Does anybody know how I can go about doing this?
Many thanks!

In addition to NSRegularExpression, you can also use NSPredicate.
NSString *filePath = #"file://Users/test/Desktop/file.txt";
NSString *matchCriteria = #"file://*/file.*";
NSPredicate *pred = [NSPredicate predicateWithFormat:#"self LIKE %#", matchCriteria];
BOOL filePathMatches = [pred evaluateWithObject:filePath];
The Predicate Programming Guide is a comprehensive document desribing how predicates work. They can be particularly useful if you have an array of items that you want to filter based on some criteria.

NSString implements these methods:
#interface NSObject (NSComparisonMethods)
- (BOOL)isLike:(NSString *)object;
- (BOOL)isCaseInsensitiveLike:(NSString *)object;
#end
They are much faster than NSPredicate and NSRegularExpression.

You can use NSRegularExpression.

Related

URL Regex Crashed iOS App

I have URL Regex Method like that;
NSString *urlRegEx = #"(http://|https://|www.)((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*)|([#^?'+!&%.#=*]))+((\\w)*|([0-9]*|([#^?'+!&%.#=*])))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
NSArray *urlArray = [textView.text componentsSeparatedByString:#" "];
It works great but however if URL contains '-' or '_' application crashed. Do you have any idea about problem?
Ok folks i have found solution like that;
NSString *urlRegEx = #"(http://|https://|www.)((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*)|([-_#^?'+!&%.#=*]))+((\\w)*|([0-9]*|([-_#^?'+!&%.#=*])))+";

iPhone: How to find string in a complete string

How to get the a certain string from a complete string.
For ex: I have a complete string like below.
"http://serverurl.com/mediadata/Album.wav";
I need to get "Album.wav" from the above string. The name varies with different url string. How to get it?
Thanks.
You could use path components:
NSString fileName = [URLstring lastPathComponent];
You can also use the NSString class methods, those that begin with rangeOfString:
- (NSRange)rangeOfString:(NSString *)aString;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(NSLocale *)locale;
You need to use NSScanner probably and scan up to the 4th slash. whats left after the scan would be the string you want.
Edited
However as with what Richard said if your url isn't going to change a simple path component will work since NSString parses file paths for you. heres an example.
NSArray *urlStrings = [NSArray arrayWithObjects:#"http://serverurl.com/mediadata/Album.wav",
#"http://serverurl.com/mediadata/NewAlbum.wav",
#"http://serverurl.com/mediadata/OtherAlbum.mp3", nil];
for (NSString *url in urlStrings) {
NSLog(#"%#",[url lastPathComponent]);
}
Output
2012-04-15 09:01:15.878 NSScanner[6448:f803] Album.wav
2012-04-15 09:01:15.880 NSScanner[6448:f803] NewAlbum.wav
2012-04-15 09:01:15.881 NSScanner[6448:f803] OtherAlbum.mp3

iOS - return number of files matching a naming scheme

Is there an easy way to return a number of files that conform to a set naming scheme? Trying to make cheap and easy image sequence player. I have the heavy lifting done but currently have to pass it the number of files in each sequence which is a pain to update.
example
Image1_000 Image1_001 Image2_000 Image2_001 Image2_002
So if the naming scheme was set to Image2_ it would return 3 and if the naming scheme was set to Image1_ it would return 2.
You can achieve this pretty easily with the help of NSPredicate, where you define a regular expression like syntax. This happens like so:
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRoot error:nil];
NSArray *onlyImagesStartWithTwo = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self BEGINSWITH 'Image2_'"]];
This NSArray *onlyImagesStartWithTwo will have all images starting with Image2_.
Hope this helps...
if these are NSStrings in an NSArray:
int counter = 0;
for (NSString *str in strArray) {
if ([[[str componentsSeperatedByString:#"_"] objectAtIndex:0] isEqualToString:namingScheme]){
counter++;
}
}

How to selectively trim an NSMutableString?

I would like to know how to selectively trim an NSMutableString. For example, if my string is "MobileSafari_2011-09-10-155814_Jareds-iPhone.plist", how would I programatically trim off everything except the word "MobileSafari"?
Note : Given the term programatically above, I expect the solution to work even if the word "MobileSafari" is changed to "Youtube" for example, or the word "Jared's-iPhone" is changed to "Angela's-iPhone".
Any help is very much appreciated!
Given that you always need to extract the character upto the first underscore; use the following method;
NSArray *stringParts = [yourString componentsSeparatedByString:#"_"];
The first object in the array would be the extracted part you need I would think.
TESTED CODE: 100% WORKS
NSString *inputString=#"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *array= [inputString componentsSeparatedByString:#"_"];
if ([array count]>0) {
NSString *resultedString=[array objectAtIndex:0];
NSLog(#" resultedString IS - %#",resultedString);
}
OUTPUT:
resultedString IS - MobileSafari
If you know the format of the string is always like that, it can be easy.
Just use NSString's componentsSeparatedByString: documented here.
In your case you could do this:
NSString *source = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *seperatedSubStrings = [source componentsSeparatedByString:#"_"];
NSString *result = [seperatedSubStrings objectAtIndex:0];
#"MobileSafari" would be at index 0, #"2011-09-10-155814" at index 1, and #"Jareds-iPhone.plist" and at index 2.
Try this :
NSString *strComplete = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *arr = [strComplete componentsSeparatedByString:#"_"];
NSString *str1 = [arr objectAtIndex:0];
NSString *str2 = [arr objectAtIndex:1];
NSString *str3 = [arr objectAtIndex:2];
str1 is the required string.
Even if you change MobileSafari to youtube it will work.
So you'll need an NSString variable that'll hold the beginning of the string you want to truncate. After that one way could be to change the string and the variable string values at the simultanously. Say, teh Variable string was "Youtube" not it is changed to "MobileSafari" then the mutable string string should change from "MobileSafari_....." to "YouTube_......". And then you can get the variable strings length and used the following code to truncate the the mutable string.
NSString *beginningOfTheStr;
.....
theMutableStr=[theMutableStr substringToIndex:[beginningOfTheStrlength-1]];
See if tis works for you.

How to check if a string contains English letters (A-Z)?

How can I check whether a string contains the English Letters (A through Z) in Objective-C?
In PHP, there is preg_match method for that.
One approach would be to use regular expressions — the NSRegularExpression class. The following demonstrates how you could detect any English letters, but the pattern could be modified to match only if the entire string consists of such letters. Something like ^[a-zA-Z]*$.
NSRegularExpression *regex = [[[NSRegularExpression alloc]
initWithPattern:#"[a-zA-Z]" options:0 error:NULL] autorelease];
// Assuming you have some NSString `myString`.
NSUInteger matches = [regex numberOfMatchesInString:myString options:0
range:NSMakeRange(0, [myString length])];
if (matches > 0) {
// `myString` contains at least one English letter.
}
Alternatively, you could construct an NSCharacterSet containing the characters you're interested in and use NSString's rangeOfCharacterFromSet: to find the first occurrence of any one. I should note that this method only finds the first such character in the string. Maybe not what you're after.
Finally, I feel like you could do something with encodings, but haven't given this much thought. Perhaps determine if the string could be represented using ASCII (using canBeConvertedToEncoding:) and then check for numbers/symbols?
Oh, and you could always iterate over the string and check each character! :)
You can use simple NSPredicate test.
NSString *str = #"APPLE";
NSString *regex = #"[A-Z]+";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL result = [test evaluateWithObject:str];
You could also use NSCharacterSet and use the rangeOfCharacterFromSet: method to see if the returned NSRange is the entire range of the string. characterSetWithRange would be a good place to start to create your characterSet.
You can use the NSRegularExpression Class (Apple's documentation on the class can be viewed here)