Is there any way to split a string into multiple string based on character count (not delimiter)? - objective-c

So if I have "7A7F6E88920AB8271A" and I want to split it into an array of strings with same amount of character count, like "7A", "7F", "6E", "88", ... is there any method ready for this, or I have to manually make it on objective C? Thanks.

I am not an objective-c expert, but the following might lead you in the right direction (Regular Expressions)
NSRegularExpression regexp = [NSRegularExpression
regularExpressionWithPattern:#"(\\w){2}"
options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:string options:0
range:NSMakeRange(0, [string length])];
The RegExp (\\w){2}should find all 2-length character words and each of them are in the matches array.
Constructed from examples on this page: https://developer.apple.com/reference/foundation/nsregularexpression

Related

Regular expression to match multiple occurrences of characters between delimiters

I'm trying to use NSRegularExpression to find multiple occurrences of substrings that are delimited by a pair of % characters, for example if I want to extract "%FirstOccurence%enter code here" as a substring from the following:
"stuff %FirstOccurence% more stuff"
Then I can do this:
NSString* const pattern = #"[%].+[%]";
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern
options:0
error:nil];
NSRange range = NSMakeRange(0, [testData length]);
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:testData options:0 range: range];
However if the string contains something like this:
"stuff %FirstOccurence% more stuff %Second Occurrence% yet more stuff"
Then my regex will match this: "%FirstOccurence% more stuff %Second Occurrence%" i.e. the NSTextCheckingResult will contain one range.
What should the regex/code be to make the NSTextCheckingResult contain two ranges of %FirstOccurence% and %Second Occurrence% rather than the one larger range?
It appears you want to be calling matchesInString:options:range: which returns all the matching results.
NSArray *matches = [regex matchesInString:string
options:0
range:NSMakeRange(0, [string length])];
See https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSRegularExpression

Objective C - Split string into array

How would I do this? I'm new to Objective-C but I can't find anything that would help me do this.
NSArray *splitLine = [currentLine componentsSeparatedByString:#":%#",notNumber];
Where notNumber is a string that represents anything that isn't a number. So I want to separate a string where there are colons separated by strings that aren't numbers. (I want to avoid splitting at times i.e. 3:00pm, but split at iCal parameters like DESCRIPTION: and LOCATION:.)
You can do this in several steps, like this. I have not compiled this code, but it should at least give you an idea of what to do.
1) Create a regex object to match your separators:
NSString *regexString = #"DESCRIPTION:\s|LOCATION:\s"; // or whatever makes sense for your scenario
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:regexString
options:NSRegularExpressionCaseInsensitive
error:nil];
2) Replace all the different separators matching your regex with just one separator:
NSRange range = NSMakeRange(0, string.length);
NSString *string2 = [regex stringByReplacingMatchesInString:string
options:0
range:range
withTemplate:#"SEPARATOR"];
3) Split the string!
NSArray *elements = [string2 componentsSeparatedByString:#"SEPARATOR"];
Shortest solution for splitting string.
NSString *str = #"Please split me to form array of words";
NSArray *wordsArray = [str componentsSeparatedByString:#" "];
You can use regular expressions!
Using the pattern (I believe this is the core of your question):
pattern = #"(?<=[^0-9]):(?=[^0-9])"
This pattern will only match ':' symbols not surrounded by numbers.
Then replace with a dummy value that won't show in your data
dummy = #"NEVERSEETHIS"
NSRegularExpressions *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSRange range = NSMakeRange(0, [string length])
NSString *modified= [regex replaceMatchesInString:yourString options:0 range:range withTemplate:dummy];
and finally, split
return [modified componentsSeparatedByString:dummy];

Why is my NSRegularExpression pattern not working?

I have the following string:
NSString *string = #"she seemed \x3cem\x3ereluctant\x3c/em\x3e to discuss the matter";
I want the final string to be: "she seemed reluctant to discuss the matter"
I have the following pattern:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/\\x[0-9a-f]{2}/"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NSLog(#"%#", NSStringFromRange(matchRange));
}
However, I get an error saying the pattern is invalid. What am I doing wrong?
The pattern you need is:
#"\\\\x[0-9a-f]{2}"
The backslash is special to both Obj-C and the RE parser - so you need to create an Obj-C string with two \'s so the RE parser can then end up with one.
Also there are no open/close delimiters in the string - you're thinking of another programming language there!
You can save yourself some regex troubles by using the NSString method
stringByReplacingOccurrencesOfString:withString:
Or
stringByReplacingOccurrencesOfString:withString:options:range:

Dealing with separation characters within quotes when using componentsSeparatedByCharactersInSet

I'm trying to separate a string by the use of a comma. However I do not want to include commas that are within quoted areas. What is the best way of going about this in Objective-C?
An example of what I am dealing with is:
["someRandomNumber","Some Other Info","This quotes area, has a comma",...]
Any help would be greatly appreciated.
Regular expressions might work well for this, depending on your requirements. For example, if you're always trying to match items that are enclosed in double quotes, then the it might be easier to look for the quotes rather than worrying about the commas.
For example, you could do something like this:
NSString *pattern = #"\"[^\"]*\"";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NString *substring = [string substringWithRange:matchRange];
// do whatever you need to do with the substring
}
This code looks for a sequence of characters enclosed in quotes (the regex pattern "[^"]*"). Then for each match it extracts the matched range as a substring.
If that doesn't exactly match your requirements, it shouldn't be too difficult to adapt it to use a different regex pattern.
I'm not in a position to test this code at the moment, so my apologies if there are any errors. Hopefully the basic concept should be clear.

NSRegularExpression not matching

So I have a string:
users/9881570/?access_token=
that I try to match with the regex:
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:#"users/\\d/?access_token=" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray* wordArray = [regex matchesInString:self.currentRequestURL_
options:0 range:NSMakeRange(0, [self.currentRequestURL_ length])];
However, the wordArray has a count of 0. Why is this not matching?
For one thing, you need to escape the question mark, and for another you need a plus sign (+) after your \d to indicate 1 or more numbers. As it is now you only look for one digit.
#"users/\\d+/\\?access_token="
Because the question mark is a special character in regular expressions, and it needs to be escaped.