RegExKitLite Expression Question - iphone

I'm having trouble coming up with an RegExKitLite expression that will match. I'm parsing a string and I want it to grab everything till it comes upon the first occurrence of a colon
What would be the expression in RegExKitLite to do that?
Thanks!

This regex will match everything from the start until (but excluding) the first colon:
^[^:]*
To include the first colon is as simple as putting it on the end:
^[^:]*:
So, to use either of those with RegexKitLite, you can do:
NSString * firstItem = [someString stringByMatching:#"^[^:]*" capture:0];
Note how there is no parentheses - since * is greedy you can simply use the negated class and use captured group 0 (i.e. the whole match).
It's worth noting that most languages will include functions that allow you to do this with a regular function, for example ListFirst(MyString,':') or MyString.split(':')[0]
I suspect Objective-C has something similar to this ... yep, see here
NSString *string = #"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: #":"];

To do this specifically with RegexKitLite, you'll need to do the following:
Add the RegexKitLite.h/.m files to your project
Import RegexKitLite.h into the file where you need to use regular expressions
Use the following to grab the stuff before the colon:
NSString * everythingBeforeTheColon = [someString stringByMatching:#"([^:]*):" capture:1];

I just updated my SO answer here, so I figured I'd use that to benchmark the standard foundation componentsSeparatedByString: and RegexKitLites componentsSeparatedByRegex:. The line of code inside the for() loop for each was (essentially):
NSString *string = #"oop:ack:bork:greeble:ponies";
for() { NSArray *chunks = [string componentsSeparatedByString: #":"]; }
for() { NSArray *chunks = [string componentsSeparatedByRegex: #":"]; }
Times returned were (time is in microseconds per operation):
componentsSeparatedByString: 3.96810us
componentsSeparatedByRegex: 2.46155us
EDIT:
I thought I'd go one better: How to use RegexKitLite to create a NSArray of NSArrays from a string containing multiple lines of colon separated data (ie, /etc/passwd). Modified from the comma separated value example in the RegexKitLite documentation. When finished, the variable splitLinesArray contains the finished product.
NSString *theString = #"a:b:c\n1:2:3\nX:Y:Z\n"; // An example string to work on.
NSArray *linesArray = [theString componentsSeparatedByRegex:#"(?:\r\n|[\n\v\f\r\\x85\\p{Zl}\\p{Zp}])"];
id splitLines[[linesArray count]];
NSUInteger splitLinesIndex = 0UL;
for(NSString *lineString in linesArray) { splitLines[splitLinesIndex++] = [lineString componentsSeparatedByRegex:#":"]; }
NSArray *splitLinesArray = [NSArray arrayWithObjects:splitLines count:splitLinesIndex];

Related

Convert or Print CGPDFStringRef string

How to convert a CGPDFStringRef to unicode char? I have used CGPDFStringCopyTextString to get the string and then [string characterAtIndex:i] to cast to unichar, is this the right way? or is there any way to get the bytes of the string and convert to unicode directly?
Need some guidance here.
NSString is capable of handling of unicode characters itself, you just need to convert the CGPDFString to NSString and further you can use it as follows:
NSString *tempStr = (NSString *)CGPDFStringCopyTextString(objectString);
although UPT's answer is correct, it will produce a memory leak
from the documentation:
CGPDFStringCopyTextString
"...You are responsible for releasing this object."
the correct way to do this would be:
CFStringRef _res = CGPDFStringCopyTextString(pdfString);
NSString *result = [NSString stringWithString:(__bridge NSString *)_res];
CFRelease(_res);
It's not a bad idea, even if you can access the CGPDFString directly using CGPDFStringGetBytePtr. You will also need CGPDFStringGetLength to get the string length, as it may not be null-terminated.
See the documentation for more info

Objective C: Compare Array Element to String

Greetings,
I'm trying to simply compare a NSString to an NSArray.
Here is my code:
NSString *username=uname.text;
NSString *regex=#"^[a-zA-Z0-9-_.]{3,20}$";
NSArray *matchArray=nil;
matchArray=[username componentsMatchedByRegex:regex];
if(matchArray[0] == "asdf"){ //this line causes the problem!
NSLog(#"matchArray %#",matchArray);
}
I get an "invalid operands to binary ==" error.
How can I compare the string?
Many thanks in advance,
You are trying to compare an NSString to a C string (char *), which is wrong. matchArray is an NSArray so you cannot treat it as a C array either, you have to use its objectAtIndex: method and pass in the index.
Use this instead:
if ([[matchArray objectAtIndex:0] isEqualToString:#"asdf"]) {
NSLog(#"matchArray %#", matchArray);
}
Addressing your comments, the reason why isEqualToString: does not show up in autocomplete is because Xcode cannot guess that matchArray contains NSStrings (it only knows it contains ids, that is, arbitrary Objective-C objects). If you really wanted to be sure, you can perform an explicit cast, but it doesn't matter if you don't:
if ([(NSString *)[matchArray objectAtIndex:0] isEqualToString:#"asdf"]) {
NSLog(#"matchArray %#", matchArray);
}
you want to use -objectAtIndex to get the array element. NOT the C array accessor syntax
try to use:
[[matchArray objectAtIndex:0] isEqualToString:#"asdf"];
anyway the string "asdf" should be #"asdf"

How can I remove quotes from an NSString?

I am trying to remove quotes from something like:
"Hello"
so that the string is just:
Hello
Check out Apple's docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
You probably want:
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
So, something like this should work:
newString = [myString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
I only wanted to remove the first quote and the last quote, not the quotes within the string so here's what I did:
challengeKey = #"\"I want to \"remove\" the quotes.\"";
challengeKey = [challengeKey substringFromIndex:1];
challengeKey = [challengeKey substringToIndex:[challengeKey length] - 1];
Hope this helps others looking for the same thing. NSLog and you'll get this output:
I want to "remove" the quotes.

NSString returning jibberish

Totally lost with this one. Here's my code:
theColor = [NSString stringWithFormat:#"white"];
NSLog(#"%s", theColor);
Which is returing:
†t†å
I must be doing something stupid, but can not figure it out for the life of me.
Change your print to:
NSLog(#"%#", theColor);
Hope it helps.
The thing is that %s expects a C-string (char array with a NULL terminator) and you are passing a NSString instance which is not the same as a C-string. The modifier you need in a format to print NSString content is %#.
%s is for printing C-style strings.
%# is for printing Objective-C objects (like NSString).
BTW: “theColor = [NSString stringWithFormat:#"white"];” – why not “theColor = #"white";”?
Greetings

How to get the string value from a string which contains ","?

I have a string value where it contains comma. Ex:- 1,234. I want to get the value of the string where i need only 1234. Can you please help me...
Instead of manually stripping out the commas, it might be more elegant (and less error-prone if you support different locales) to use an NSNumberFormatter to convert the string to a number.
NSString *myString = "1,234";
NSString *resultString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];
If you want to strip the comma then: -
NSString *string = #"1,234";
string = [string stringByReplacingOccurrencesOfString:#"," withString:#""];
This should return you a string with just 1234 in it.
By 'getting the value' do you mean, converting this to a NSNumber object? If so use this
NSNumber *numberFromString = [NSNumber numberWithInteger:[string integerValue]];
I don't know that framework/language, but if an integer converter won't work, then strip out the commas by replacing them with null from the string and then convert to an integer.