Apply regular expression repeatedly - iphone

I've got text expressions like this:
HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'
I want to extract the following text pieces:
HIUPD:bla2bla2'
And
HIUPD:bla3bla3'
My Objective-C code for this looks like this:
-(void) ermittleKonten:(NSString*) bankNachricht
{
NSRegularExpression* regexp;
NSTextCheckingResult* tcr;
regexp = [NSRegularExpression regularExpressionWithPattern:#"HIUPD.*'" options:0 error:nil];
int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])];
for( int i = 0; i < numAccounts; ++i ) {
tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange( 0, [bankNachricht length] )];
NSString* HIUPD = [bankNachricht substringWithRange:tcr.range];
NSLog(#"Found text is:\n%#", HIUPD);
}
}
In the Objective-C code numAccounts is 1, but should be 2. And the string that is found is "HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'"
I tested the regular expression pattern with an online tool ( http://www.regexplanet.com/simple/index.html ). In the online tool it works fine and delivers 2 results as I want it to be.
But I would like to have the same result in the ios code, i.e. "HIUPD:bla2bla2'" and "HIUPD:bla3bla3'". What is wrong with the pattern?

You're doing greedy matching with the .*, so the regular expression catches as much as it can in the .*. You should be doing .*?, or [^']*, so that the * can't match a '.

Related

Formatting an String

I have an output string in this format .
I need to format the string such that i can display the URL separately and my Content, the description separately. Is there any functions , so i can format them easily ?
The code :
NSLog(#"Description %#", string);
The OUTPUT String:
2013-07-28 11:13:59.083 RSSreader[4915:c07] Description
http://www.apple.com/pr/library/2013/07/23Apple-Reports-Third-Quarter-Results.html?sr=hotnews.rss
Apple today announced financial results for its fiscal 2013 third quarter ended
June 29, 2013. The Company posted quarterly revenue of $35.3 billion and quarterly
net profit of $6.9 billion, or $7.47 per diluted share.
Apple sold 31.2 million iPhones, which set a June quarter record.
You should extract URL from string, then display it in formatted way.
A simple way to extracting URL is regular expressions (RegEX).
After extracting URL you can replace it with nothing:
str = [str stringByReplacingOccurrencesOfString:extractedURL
withString:#""];
You can use this :
https://stackoverflow.com/a/9587987/305135
If description string separated by line break (\n), you can do this:
NSArray *items = [yourString componentsSeparatedByString:#"\n"];
Regex is a good idea.
But there is a default way of detecting URLs within a String in Objective C, NSDataDetector.
NSDataDetector internally uses Regex.
NSString *aString = #"YOUR STRING WITH URLs GOES HERE"
NSDataDetector *aDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *theMatches = [aDetector matchesInString:aString options:0 range:NSMakeRange(0, [aString length])];
for (int anIndex = 0; anIndex < [theMatches count]; anIndex++) {
// If needed, Save this URL for Future Use.
NSString *anURLString = [[[theMatches objectAtIndex:anIndex] URL] absoluteString];
// Replace the Url with Empty String
aTitle = [aTitle stringByReplacingOccurrencesOfString:anURLString withString:#""];
}

how to solve a conditional equation in iOS

I want to solve a conditional equation in iOS:
The equation I get from database is in NSString format, for example:
if((height > 0), (weight+ 2 ), ( weight-1 ) )
As per our understanding, if I parse the above string and separateheight>0condition, it will be in the NSString format. But to evaluate it how do I convert the string to a conditional statement?
Once the conditional statement is obtained the equation can be solved by converting it to a ternary equation as follows:
Bool status;
NSString *condition=#” height>0”;
If(condition)    //But condition is treated as a string and not as a conditional statement.
{
status=True;
}
else
{
status=False;
}
Return status ? weight+ 2 : weight-1;`
Also the equations can dynamically change, so they cannot be hard coded. In short how do I solve this equation which I get as a NSString.
Thank you for your patience!
DDMathParser author here...
To expand on Jonathan's answer, here's how you could do it entirely in DDMathParser. However, to parse the string as-is, you'll need to do two things.
First, you'll need to create an if function:
DDMathEvaluator *evaluator = [DDMathEvaluator sharedMathEvaluator];
[evaluator registerFunction:^DDExpression *(NSArray *args, NSDictionary *vars, DDMathEvaluator *eval, NSError *__autoreleasing *error) {
if ([args count] == 3) {
DDExpression *condition = [args objectAtIndex:0];
DDExpression *resultExpression = nil;
NSNumber *conditionValue = [condition evaluateWithSubstitutions:vars evaluator:eval error:error];
if ([conditionValue boolValue] == YES) {
resultExpression = [args objectAtIndex:1];
} else {
resultExpression = [args objectAtIndex:2];
}
NSNumber *result = [resultExpression evaluateWithSubstitutions:vars evaluator:eval error:error];
return [DDExpression numberExpressionWithNumber:result];
}
return nil;
} forName:#"if"];
This creates the if() function, which takes three parameters. Depending on how the first parameter evaluates, it either evaluates to the result of the second or third parameter.
The other thing you'll need to do is tell the evaluator what height and weight mean. Since they don't start with a $ character, they get interpreted as functions, and not variables. If they started with a $, then it would be as simple as evaluating it like this:
NSString *expression = #"if(($height > 0), ($weight+ 2 ), ( $weight-1 ) )";
NSDictionary *variables = #{#"height" : #42, #"weight" : #13};
NSNumber *result = [expression evaluateWithSubstitutions:variables evaluator:evaluator error:nil];
However, since they don't start with a $, they're functions, which means you need to tell the evaluator what the functions evaluate to. You could do this by creating functions for both height and weight, just like you did for if:
[evaluator registerFunction:^DDExpression *(NSArray *args, NSDictionary *vars, DDMathEvaluator *eval, NSError **error) {
return [DDExpression numberExpressionWithNumber:#42];
} forName:#"height"];
Alternatively, you could make it a bit more dynamic and use the functionResolver block of DDMathEvaluator, which is a block that returns a block (woooooo) and would look like this:
NSDictionary *values = #{#"height": #42, #"weight": #13};
[evaluator setFunctionResolver:^DDMathFunction(NSString *name) {
DDMathFunction f = ^(NSArray *args, NSDictionary *vars, DDMathEvaluator *eval, NSError **error) {
NSNumber *n = [values objectForKey:name];
if (!n) { n = #0; }
return [DDExpression numberExpressionWithNumber:n];
};
return f;
}];
With those two pieces in place (registering if and providing the values of height and weight), you can do:
NSString *expression = #"if((height > 0), (weight+ 2 ), ( weight-1 ) )";
NSNumber *result = [expression evaluateWithSubstitutions:nil evaluator:evaluator error:nil];
... and get back the proper result of #15.
(I have plans to make DDMathParser allow unknown functions to fall back to provided variable values, but I haven't quite finished it yet)
you will have to write your own interpreter or find one that supports this kind of expressions.
The first part (the condition) can be evaluated by NSPredicate. For the second part (the calculation) you will need some math expression evaluation. Try this out https://github.com/davedelong/DDMathParser. Maybe you can do both with DDMathParser but i am not sure.

Trim string from END

I want to string string from the end of string, is there any api function of string which ONLY removes Space and Newline from END of string.
I wrote manual code to search character from end of string and remove space and newline but it may slow the process.
API function needed..
Thanks in advance
try this one may be it helps you,
-(NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for ( i = [strtoremove length]; i >0; i--){
if (![[NSCharacterSet whitespaceCharacterSet] characterIsMember:charBuffer[i - 1]]){
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
and
NSString *string = #" this text has spaces before and after ";
NSString *trimmedString = [self removeEndSpaceFrom:string];
NSLog(#"%#",trimmedString);

How to extract email address from string using NSRegularExpression

I am making an iphone application. I have a scenario where i have a huge string, which has lot of data, and i would like to extract only email addresses from the string.
For example if the string is like
asdjasjkdh asdhajksdh jkashd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com
i should extract "sample#email.com" and "test#gmail.com"
and i also want to extract only date, from the string
For example if the string is like
asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com
i should extract "01/01/2012" and "12/11/2012"
A small code snipet, will be very helpful.
Thanks in advance
This will do what you want:
// regex string for emails (feel free to use a different one if you prefer)
NSString *regexString = #"([A-Za-z0-9_\\-\\.\\+])+\\#([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]+)";
// experimental search string containing emails
NSString *searchString = #"asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com";
// track regex error
NSError *error = NULL;
// create regular expression
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:&error];
// make sure there is no error
if (!error) {
// get all matches for regex
NSArray *matches = [regex matchesInString:searchString options:0 range:NSMakeRange(0, searchString.length)];
// loop through regex matches
for (NSTextCheckingResult *match in matches) {
// get the current text
NSString *matchText = [searchString substringWithRange:match.range];
NSLog(#"Extracted: %#", matchText);
}
}
Using your sample string above:
asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com
The output is:
Extracted: sample#email.com
Extracted: test#gmail.com
To use the code, just set searchString to the string you want to search. Instead of the NSLog() methods, you'll probably want to do something with the extracted strings matchText. Feel free to use a different regex string to extract emails, just replace the value of regexString in the code.
NSArray *chunks = [mylongstring componentsSeparatedByString: #" "];
for(int i=0;i<[chunks count];i++){
NSRange aRange = [chunks[i] rangeOfString:#"#"];
if (aRange.location !=NSNotFound) NSLog(#"email %#",chunks[i] );
}
You can use this regex to match emails
[^\s]*#[^\s]*
and this regex to match dates
\d+/\d+/\d+

How to check if NSString is contains a numeric value?

I have a string that is being generate from a formula, however I only want to use the string as long as all of its characters are numeric, if not that I want to do something different for instance display an error message.
I have been having a look round but am finding it hard to find anything that works along the lines of what I am wanting to do. I have looked at NSScanner but I am not sure if its checking the whole string and then I am not actually sure how to check if these characters are numeric
- (void)isNumeric:(NSString *)code{
NSScanner *ns = [NSScanner scannerWithString:code];
if ( [ns scanFloat:NULL] ) //what can I use instead of NULL?
{
NSLog(#"INSIDE IF");
}
else {
NSLog(#"OUTSIDE IF");
}
}
So after a few more hours searching I have stumbled across an implementation that dose exactly what I am looking for.
so if you are looking to check if their are any alphanumeric characters in your NSString this works here
-(bool) isNumeric:(NSString*) hexText
{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:hexText];
if (number != nil) {
NSLog(#"%# is numeric", hexText);
//do some stuff here
return true;
}
NSLog(#"%# is not numeric", hexText);
//or do some more stuff here
return false;
}
hope this helps.
Something like this would work:
#interface NSString (usefull_stuff)
- (BOOL) isAllDigits;
#end
#implementation NSString (usefull_stuff)
- (BOOL) isAllDigits
{
NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
return r.location == NSNotFound && self.length > 0;
}
#end
then just use it like this:
NSString* hasOtherStuff = #"234 other stuff";
NSString* digitsOnly = #"123345999996665003030303030";
BOOL b1 = [hasOtherStuff isAllDigits];
BOOL b2 = [digitsOnly isAllDigits];
You don't have to wrap the functionality in a private category extension like this, but it sure makes it easy to reuse..
I like this solution better than the others since it wont ever overflow some int/float that is being scanned via NSScanner - the number of digits can be pretty much any length.
Consider NSString integerValue - it returns an NSInteger. However, it will accept some strings that are not entirely numeric and does not provide a mechanism to determine strings which are not numeric at all. This may or may not be acceptable.
For instance, " 13 " -> 13, "42foo" -> 42 and "helloworld" -> 0.
Happy coding.
Now, since the above was sort of a tangent to the question, see determine if string is numeric. Code taken from link, with comments added:
BOOL isNumeric(NSString *s)
{
NSScanner *sc = [NSScanner scannerWithString: s];
// We can pass NULL because we don't actually need the value to test
// for if the string is numeric. This is allowable.
if ( [sc scanFloat:NULL] )
{
// Ensure nothing left in scanner so that "42foo" is not accepted.
// ("42" would be consumed by scanFloat above leaving "foo".)
return [sc isAtEnd];
}
// Couldn't even scan a float :(
return NO;
}
The above works with just scanFloat -- e.g. no scanInt -- because the range of a float is much larger than that of an integer (even a 64-bit integer).
This function checks for "totally numeric" and will accept "42" and "0.13E2" but reject " 13 ", "42foo" and "helloworld".
It's very simple.
+ (BOOL)isStringNumeric:(NSString *)text
{
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:text];
return [alphaNums isSupersetOfSet:inStringSet];
}
Like this:
- (void)isNumeric:(NSString *)code{
NSScanner *ns = [NSScanner scannerWithString:code];
float the_value;
if ( [ns scanFloat:&the_value] )
{
NSLog(#"INSIDE IF");
// do something with `the_value` if you like
}
else {
NSLog(#"OUTSIDE IF");
}
}
Faced same problem in Swift.
In Swift you should use this code, according TomSwift's answer:
func isAllDigits(str: String) -> Bool {
let nonNumbers = NSCharacterSet.decimalDigitCharacterSet()
if let range = str.rangeOfCharacterFromSet(nonNumbers) {
return true
}
else {
return false
}
}
P.S. Also you can use other NSCharacterSets or their combinations to check your string!
For simple numbers like "12234" or "231231.23123" the answer can be simple.
There is a transformation law for int numbers: when string with integer transforms to int (or long) number and then, again, transforms it back to another string these strings will be equal.
In Objective C it will looks like:
NSString *numStr=#"1234",*num2Str=nil;
num2Str=[NSString stringWithFormat:#"%lld",numStr.longlongValue];
if([numStr isEqualToString: num2Str]) NSLog(#"numStr is an integer number!");
By using this transformation law we can create solution
to detect double or long numbers:
NSString *numStr=#"12134.343"
NSArray *numList=[numStr componentsSeparatedByString:#"."];
if([[NSString stringWithFormat:#"%lld", numStr.longLongValue] isEqualToString:numStr]) NSLog(#"numStr is an integer number");
else
if( numList.count==2 &&
[[NSString stringWithFormat:#"%lld",((NSString*)numList[0]).longLongValue] isEqualToString:(NSString*)numList[0]] &&
[[NSString stringWithFormat:#"%lld",((NSString*)numList[1]).longLongValue] isEqualToString:(NSString*)numList[1]] )
NSLog(#"numStr is a double number");
else
NSLog(#"numStr is not a number");
I did not copy the code above from my work code so can be some mistakes, but I think the main point is clear.
Of course this solution doesn't work with numbers like "1E100", as well it doesn't take in account size of integer and fractional part. By using the law described above you can do whatever number detection you need.
C.Johns' answer is wrong. If you use a formatter, you risk apple changing their codebase at some point and having the formatter spit out a partial result. Tom's answer is wrong too. If you use the rangeOfCharacterFromSet method and check for NSNotFound, it'll register a true if the string contains even one number. Similarly, other answers in this thread suggest using the Integer value method. That is also wrong because it will register a true if even one integer is present in the string. The OP asked for an answer that ensures the entire string is numerical. Try this:
NSCharacterSet *searchSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
Tom was right about this part. That step gives you the non-numerical string characters. But then we do this:
NSString *trimmedString = [string stringByTrimmingCharactersInSet:searchSet];
return (string.length == trimmedString.length);
Tom's inverted character set can TRIM a string. So we can use that trim method to test if any non numerals exist in the string by comparing their lengths.