Extract substring from a string in iOS? - ios

Is there any way to extract substring from a string like below
My real string is "NS09A" or "AB455A" but i want only "NS09" or "AB455" (upto the end of numeric part of original string).
How can i extract this?
I saw google search answers like using position of starting and endinf part of substring we can extract that ,But here any combination of "Alphabets+number+alphabets" .I need only " "Alphabets+number"

Perhaps not everybody will agree, but I like regular expressions. They allow to specify
precisely what you are looking for:
NSString *string = #"AB455A";
// One or more "word characters", followed by one or more "digits":
NSString *pattern = #"\\w+\\d+";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string
options:NSMatchingAnchored
range:NSMakeRange(0, [string length])];
if (match != nil) {
NSString *extracted = [string substringWithRange:[match range]];
NSLog(#"%#", extracted);
// Output: AB455
} else {
// Input string is not of the expected form.
}

Try This:-
NSString *str=#"ASRF12353FYTEW";
NSString *resultStr;
for(int i=0;i<[str length];i++){
NSString *character = [str substringFromIndex: [str length] - i];
if([character intValue]){
resultStr=[str substringToIndex:[str length]-i+1];
break;
}
}
NSLog(#"RESUKT STRING %#",resultStr);

I tested this code:
NSString *originalString = #"NS09A";
// Intermediate
NSString *numberString;
NSString *numberString1;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
[scanner scanUpToCharactersFromSet:numbers intoString:&numberString];
[scanner scanCharactersFromSet:numbers intoString:&numberString1];
NSString *result=[NSString stringWithFormat:#"%#%#",numberString,numberString1];
NSLog(#"Finally ==%#",result);
Hope it Help You
OUTPUT
Finally ==NS09
UPDATE:
NSString *originalString = #"kirtimali#gmail.com";
NSString *result;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *cs1 = [NSCharacterSet characterSetWithCharactersInString:#"#"];
[scanner scanUpToCharactersFromSet:cs1 intoString:&result];
NSLog(#"Finally ==%#",result);
output:
Finally ==kirtimali

Use NSScanner and the scanUpToCharactersFromSet:intoString: method to specify which characters should be used to stop the parsing. This could be in a loop with some logic or it could be applied in conjunction with setScanLocation: if you already have a method of finding the start of each section you want to extract.
When using scanUpToCharactersFromSet:intoString: you are looking for the next invalid character. It doesn't need to be a 'special' character (in a unicode sense), just a known set of characters that aren't valid for the content you want. So, you might use:
[[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet]

You can use - (NSString *)substringWithRange:(NSRange)aRange method on NSString class to get a substring extracted. Use NSMakeRange to create the NSRange object.

Related

Extract a String out of a specific set of strings

I have a text as:
sometext[string1 string2]someText
I want to retrieve string1 and string2 as separate strings from this text
How can i parse it in objective - c?
i have found the solution
NSArray *arrayOne = [prettyFunctionString componentsSeparatedByString:#"["];
NSString *parsedOne = [arrayOne objectAtIndex:1];
NSArray *arrayTwo = [parsedOne componentsSeparatedByString:#"]"];
NSString *parsedTwo = [arrayTwo objectAtIndex:0];
NSArray *arrayThree = [parsedTwo componentsSeparatedByString:#" "];
NSString *className = [arrayThree objectAtIndex:0];
NSString *functionName = [arrayThree objectAtIndex:1];
thanks anyways
Maybe something like this could work for you
NSString * string = #"sometext[string1 string2]sometext";
NSString * pattern = #"(.*)\[(.+) (.+)\](.*)"
NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult * match = [expression firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];
if (match) {
NSString * substring1 = [string substringWithRange:[match rangeAtIndex:2]];
NSString * substring2 = [string substringWithRange:[match rangeAtIndex:3]];
// do something with substring1 and substring2
}
You can Use this Simple Approach approach
NSString *str = #"sometext[string1 string2]someText";
NSInteger loc1 = [str localizedStandardRangeOfString:#"["].location;
NSInteger loc2 = [str localizedStandardRangeOfString:#"]"].location;
NSString *resultString = [str substringWithRange:(NSRange){loc1+1,loc2-loc1}];
NSArray *resultArry = [resultString componentsSeparatedByString:#" "];
result array will contain your required Reuslt
For completeness - if you are trying to extract strings out of a string with a known pattern, then an NSScanner is the way to go.
This goes through the string in one pass.
NSString *string = #"sometext[string1 string2]someText";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSString *str1;
NSString *str2;
[scanner scanUpToString:#"[" intoString:nil]; // Scan up to the '[' character.
[scanner scanString:#"[" intoString:nil]; // Scan the '[' character and discard it.
[scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &str1]; // Scan all the characters up to the whitespace and accumulate the characters into 'str1'
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:nil]; // Scan up to the next alphanumeric character and discard the result.
[scanner scanUpToString:#"]" intoString:&str2]; // Scan up to the ']' character, accumulate the characters into 'str2'
// Log the output.
NSLog(#"First String: %#", str1);
NSLog(#"Second String: %#", str2);
Which puts the output into the console of:
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] First String: string1
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] Second String: string2

Filter new line from array of email strings

I'm trying to send emails to a list that I get from a server which is an array of emails whose output is in this format
(
"john#gmail.com\n",
"katebell#gmail.com\n"
"\nakhil#gmail.com",
"mary#gmail.com",
"timcorb\n#gmail.com
)
Now as you can see some emails have newline characters in between and those emails doesnt get sent. I'm trying to find an efficient way to filter out those newlines, my current approach is to loop through all emails and check for newline in each email and if newline exist replace it with a null string. Is there a better way to do this or should I just stick with that? Also Will my current approach cause any issues in any other scenarios?
One way you can try using NSRegularExpression like this below :-
NSArray *array=#[#"john#gmail.com\n",#"katebell#gmail.com\n",#"\nakhil#gmail.com",#"mary#gmail.com",#"timcorb\n#gmail.com"];
NSString *string =[array componentsJoinedByString: #","];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\n" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSLog(#"%#",modifiedString);
Output:-
john#gmail.com,katebell#gmail.com,akhil#gmail.com,mary#gmail.com,timcorb#gmail.com
try something like this
NSString *fileName = #"\ntest\n";
fileName = [fileName stringByReplacingOccurrencesOfString:#"\n" withString:#""];
eg.
NSString * str = #"timcorb\n#gmail.com";
str = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"%#",str);
it will Log 2014-01-10 01:01:00.256 demo[26220] timcorb#gmail.com
You can use the below code for replacing characters in a string.
NSString *email = #"\nakhi\nl#gmail.com";
NSString *actualEmail = [email stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSMutableArray* emailArray = [[NSMutableArray alloc] init];
for (int _index = 0; _index < [yourArray count]; _index++) {
[emailArray addobject:[[yourArray objectAtIndex:_index] stringByReplacingOccurrencesOfString:#"\n" withString:#""]];
}
This will give you your email array

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Is this NSScanner 's bug?

The code snippet is as follows:
unichar chars[] = {0x0030, 0x0031, 0x0032, 0x003B, 0x0E31};//the testString is "012;" plus a thai character
NSString *testString = [[NSString alloc] initWithCharacters:chars length:5];
NSLog(#"testString %#", testString);
NSScanner *theScanner = [NSScanner scannerWithString:testString];
NSString *result = nil;
[theScanner scanUpToString:#";" intoString:&result];
//[theScanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:#";"] intoString:&result];
NSLog(#"the result is %#", result);
using scanUpToString failed, however, using scanUpToCharactersFromSet works. And if the character after 0x003B is not 0x0E31, for example ,0x0030, both api works.
So I guess scanUpToString has a bug dealing with some characters.
Does anyone has better ideas?
Thank you.

Return number from NSString

I have NSString like this: #"text 932".
How I can return number from this string. Number is always at the end of string, but i can' t use stringWithRange, because number don' t have constant length. So I'm seeking for better method.
I aslo want' know how to return number from string like this #"text 3232 text". I aslo don' t know position of number.
There is any function that find number in string ?
Here is a solution that will work for both strings
NSString *myString = #"text 3232 text";
//Create a scanner with the string
NSScanner *scanner = [NSScanner scannerWithString:myString];
//Create a character set that includes all letters, whitespaces, and newlines
//These will be used as skip tokens
NSMutableCharacterSet *charactersToBeSkipped = [[NSMutableCharacterSet alloc]init];
[charactersToBeSkipped formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
[charactersToBeSkipped formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[scanner setCharactersToBeSkipped:charactersToBeSkipped];
[charactersToBeSkipped release];
//Create an int to hold the number
int i;
//Do the work
if ([scanner scanInt:&i]) {
NSLog(#"i = %d", i);
}
The output of the NSLog is
i = 3232
EDIT
To handle decimals:
float f;
if ([scanner scanFloat:&f]) {
NSLog(#"f = %f", f);
}
Update:
Updated to test whether there is a match or not, and also to handle negative/decimal numbers
NSString *inputString=#"text text -9876.234 text";
NSString *regExprString=#"-{0,1}\\d*\\.{0,1}\\d+";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:regExprString options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSRange rangeOfFirstMatch=[regex firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)].range;
if(rangeOfFirstMatch.length>0){
NSString *firstMatch=[inputString substringWithRange:rangeOfFirstMatch];
NSLog(#"firstmatch:%#",firstMatch);
}
else{
NSLog(#"No Match");
}
Original:
Here is a solution that uses regular expressions:
NSString *inputString=#"text text 0123456 text";
NSString *regExprString=#"[0-9]+";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:regExprString options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSString *firstMatch=[inputString substringWithRange:[regex firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)].range];
NSLog(#"%#",firstMatch);
output is:
0123456
If you want an actual integer from that, you can add:
NSInteger i=[firstMatch integerValue];
NSLog(#"%d",i);
Output is then: 123456

Resources