How to parse a NSString - ios

The string is myAgent(9953593875).Amt:Rs.594 and want to extract 9953593875 from it. Here is what I tried:
NSRange range = [feDetails rangeOfString:#"."];
NSString *truncatedFeDetails = [feDetails substringWithRange:NSMakeRange(0, range.location)];
NSLog(#"truncatedString-->%#",truncatedFeDetails);
This outputs: truncatedString-->AmzAgent(9953593875)

Or you do like this:
NSString *string = #"myAgent(9953593875).Amt:Rs.594.";
NSRange rangeOne = [string rangeOfString:#"("];
NSRange rangeTwo = [string rangeOfString:#")"];
if (rangeOne.location != NSNotFound && rangeTwo.location != NSNotFound) {
NSString *truncatedFeDetails = [string substringWithRange:NSMakeRange(rangeOne.location + 1, rangeTwo.location - rangeOne.location - 1)];
NSLog(#"%#",truncatedFeDetails);
}

do like
Step-1
// split the string first based on .
for example
NSString *value = #"myAgent(9953593875).Amt:Rs.594.How I get 9953593875 only";
NSArray *arr = [value componentsSeparatedByString:#"."];
NSString * AmzAgent = [arr firstObject]; // or use [arr firstObject];
NSLog(#"with name ==%#",AmzAgent);
in here u get the output of myAgent(9953593875)
Step-2
in here use replace string like
AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:#"myAgent("
withString:#""];
AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:#")"
withString:#""];
NSLog(#"final ==%#",AmzAgent);
finally you get output as 9953593875

Try this
NSString *str = #"myAgent(9953593875).Amt:Rs.594.";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(?<=\\()\\d+(?=\\))"
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *result = [str substringWithRange:[regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])].range];
//result = 9953593875

Related

Regex for a string combination

NSString *fmtpAudio = #"a=fmtp:111 ";
NSString *stereoString = #";stereo=1;sprop-stereo=1";
NSArray *componentArray = [localSdpMutableStr componentsSeparatedByString:fmtpAudio];
if (componentArray.count >= 2) {
NSString *component = [componentArray objectAtIndex: 1];
NSArray *fmtpArray = [component componentsSeparatedByString:#"\r\n"];
if (fmtpArray.count > 1) {
NSString *fmtp = [fmtpArray firstObject];
NSString *fmtpAudioOld = [NSString stringWithFormat:#"%#%#", fmtpAudio, fmtp];
fmtpAudio = [NSString stringWithFormat:#"%#%#%#", fmtpAudio, fmtp, stereoString];
NSString *stereoEnabledSDP = [NSString stringWithString: localSdpMutableStr];
stereoEnabledSDP = [stereoEnabledSDP stringByReplacingOccurrencesOfString: fmtpAudioOld withString: fmtpAudio];
localSdpMutableStr.string = stereoEnabledSDP;
}
}
Consider below example String:
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n
In the above example string, a=fmtp:111 can appear anywhere in the string.
We have to get the string between a=fmtp:111 and the next first appearance of \r\n which is av=1 in our case
Now we have to append ;stereo=1;sprop-stereo=1 to av=1 and append back to the original string.
The final output should be
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1;stereo=1;sprop-stereo=1\r\n
a=fmtp:92 av=2\r\n
Is it possible to achieve the above chunk of logic with Replace with Regex pattern?
You can use
NSError *error = nil;
NSString *fmtpAudio = #"^a=fmtp:111 .*";
NSString *stereoString = #"$0;stereo=1;sprop-stereo=1";
NSString *myText = #"a=fmtp:93 av=2\r\na=fmtp:111 av=1\r\na=fmtp:92 av=2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:fmtpAudio options:NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate: stereoString];
NSLog(#"%#", modifiedString);
Output:
a=fmtp:93 av=2
a=fmtp:111 av=1;stereo=1;sprop-stereo=1
a=fmtp:92 av=2
See the regex demo.
Details
^ - start of a line (^ starts matching line start positions due to the options:NSRegularExpressionAnchorsMatchLines option)
a=fmtp:111 - a literal string
.* - any zero or more chars other than line break chars as many as possible.
The $0 in the replacement pattern is the backreference to the whole match value.

Check if there is a word after a word (NSSTRING)

I have a fun little tricky problem. So I need to create an if statement that can detect if there is a word after a word in an array
so my code is
NSArray *words = [texfield.text componentsSeparatedByString:#" "];
int index = [words indexOfObject:#"string"];
I am not sure if I have to do something like
NSString*needle=words[index+1];
if (needle isEqualto #"") {
//There is a word after #"string";
}
What should I do?
How can I determine is there is a word after #"string"?
I appreciate all the help!! :)
Yeah, you have to:
NSArray *words = [texfield.text componentsSeparatedByString:#" "];
NSInteger index = [words indexOfObject:#"string"];
NSInteger afterIndex = index+1;
if(afterIndex<words.count) {
NSString *needle = words[index+1];
if (needle isEqualToString #"") {
//do something
}
}
NSString *yourString = #"string stackoverflow word after string regex";
NSRange yourStringRange = NSMakeRange(0, [yourString length]);
NSString *pattern = #"string\\s*([^\\s]*)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:yourString options:0 range: yourStringRange];
for (NSTextCheckingResult* match in matches) {
NSRange rangeForMatch = [match rangeAtIndex:1];
NSLog(#"word after STRING: %#", [yourString substringWithRange:rangeForMatch]);
}
Output:
word after STRING: stackoverflow
word after STRING: regex
Method componentsSeparatedByString: will give all components separated by input NSString.
Your eg. NSArray *words = [texfield.text componentsSeparatedByString:#" "];
will have all string separated by " ". So just check if any
NSInteger afterIndex = index+1;
if(afterIndex<words.count) if Yes, you have NSStringavailable.

how to convert NSString to NSArray [duplicate]

This question already has answers here:
Comma-separated string to NSArray in Objective-C
(2 answers)
Closed 8 years ago.
I have a string like
NSString* str = #"[90, 5, 6]";
I need to convert it to an array like
NSArray * numbers = [90, 5 , 6];
I did a quite long way like this:
+ (NSArray*) stringToArray:(NSString*)str
{
NSString *sep = #"[,";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *temp=[str componentsSeparatedByCharactersInSet:set];
NSMutableArray* numbers = [[NSMutableArray alloc] init];
for (NSString* s in temp) {
NSNumber *n = [NSNumber numberWithInteger:[s integerValue]];
[numbers addObject:n];
}
return numbers;
}
Is there any neat and quick way to do such conversion?
Thanks
First remove the unwanted characters from the string, like white spaces and braces:
NSString* str = #"[90, 5, 6]";
NSCharacterSet* characterSet = [[NSCharacterSet
characterSetWithCharactersInString:#"0123456789,"] invertedSet];
NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
You will have a string like this: 90,5,6. Then simply split using the comma and convert to NSNumber:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count];
for (NSString* string in arrayOfStrings) {
[arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]];
}
Using the NSString category from this response it can be simplified to:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: #"decimalNumberValue"];
NSString* str = #"[90, 5, 6]";
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"[] "];
NSArray *array = [[[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""]
componentsSeparatedByString:#","];
Try like this
NSArray *arr = [string componentsSeparatedByString:#","];
NSString *newSTR = [str stringByReplacingOccurrencesOfString:#"[" withString:#""];
newSTR = [newSTR stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray *items = [newSTR componentsSeparatedByString:#","];
You can achieve that using regular expression 
([0-9]+)
NSError* error = nil;
NSString* str = #"[90, 5, 6]";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)" options:0 error:&error];
NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
Then you have a NSArray of string, you just need to iterate it and convert the strings to number and insert them into an array.

Find dynamically word in NSString

NSString * stringExample1=#"www.mysite.com/word-4-word-1-1-word-word-2-word-817061.html";
NSString * stringExample2=#"www.mysite.com/word-4-5-1-1-word-1-5-word-11706555.html";
I try to find - and . Inside of NSString.
NSRange range = [string rangeOfString:#"-"];
NSUInteger start = range.location;
NSUInteger end = start + range.length;
NSRange rangeDot= [string rangeOfString:#"."];
NSUInteger startt = rangeDot.location;
NSUInteger endt = startt + rangeDot.length;
But it's can't be successful. It's showing first place. How can I get 817061 and 11706555 inside of Nstring?
Thank you .
This will work for you,
NSArray *strArry=[stringExample1 componentsSeparatedByString:#"-"];
NSString *result =[strArry lastObject];
NSString *resultstring= [result stringByReplacingOccurrencesOfString:#".html" withString:#""];
Are you trying to find if it contains at least one of - or . ?
You can use -rangeOfCharacterFromSet:
NSCharacterSet *CharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"-."];
NSRange range = [YourString rangeOfCharacterFromSet:CharacterSet];
if (range.location == NSNotFound)
{
// no - or . in the string
}
else
{
// - or . are present
}
Try this simple Regular Expression.
NSString * stringExample1=#"www.mysite.com/word-4-word-1-1-word-word-2-word-84354354353.html";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(\\-\\d*\\.)"
options:0
error:&error];
NSRange range = [regex rangeOfFirstMatchInString:stringExample1
options:0
range:NSMakeRange(0, [stringExample1 length])];
range = NSMakeRange(range.location+1, range.length-2);
NSString *result = [stringExample1 substringWithRange:range];
NSLog(#"%#",result);
I think the best way to find the match is by using regulars expressions with NSRegularExpression.
NSString * stringEx=#"www.mysite.com/word-4-word-1-1-word-word-2-word-817061.html";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"-(\\d*).html$"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:stringEx options:NSMatchingReportCompletion range:NSMakeRange(0, [stringEx length])];
if ([matches count] > 0)
{
NSString* resultString = [stringEx substringWithRange:[matches[0] rangeAtIndex:1]];
NSLog(#"Matched: %#", resultString);
}
Make sure you use an extra \ escape character in the regex NSString whenever needed.
UPDATE
I did a test using the two different approaches (regex vs string splitting) with the code below:
NSDate *timeBefore = [NSDate date];
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"-(\\d*).html$"
options:NSRegularExpressionCaseInsensitive
error:&error];
for (int i = 0; i < 100000; i++)
{
NSArray *matches = [regex matchesInString:stringEx options:NSMatchingReportCompletion range:NSMakeRange(0, [stringEx length])];
if ([matches count] > 0)
{
NSString* resultString = [stringEx substringWithRange:[matches[0] rangeAtIndex:1]];
}
}
NSTimeInterval timeSpent = [timeBefore timeIntervalSinceNow];
NSLog(#"Time: %.5f", timeSpent*-1);
on the simulator the differences are not significant, but running on an iPhone 4 I got the following results:
2013-11-25 10:24:19.795 NotifApp[406:60b] Time: 11.45771 // string splitting
2013-11-25 10:25:10.451 NotifApp[412:60b] Time: 7.55713 // regex
so I guess the best approach depends on case to case.

How do I get the substring between braces?

I have a string as this.
NSString *myString = #"{53} balloons";
How do I get the substring 53 ?
NSString *myString = #"{53} balloons";
NSRange start = [myString rangeOfString:#"{"];
NSRange end = [myString rangeOfString:#"}"];
if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location) {
NSString *betweenBraces = [myString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
}
edit: Added range check, thx to Keab42 - good point.
Here is what I did.
NSString *myString = #"{53} balloons";
NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:#"{}"];
NSArray *splitString = [myString componentsSeparatedByCharactersInSet:delimiters];
NSString *substring = [splitString objectAtIndex:1];
the substring is 53.
For Swift 4.2:
if let r1 = string.range(of: "{")?.upperBound,
let r2 = string.range(of: "}")?.lowerBound {
print (String(string[r1..<r2]))
}
You can use a regular expression to get the number between the braces. It might seem a bit complicated but the plus side is that it will find multiple numbers and the position of the number doesn't matter.
Swift 4.2:
let searchText = "{53} balloons {12} clowns {123} sparklers"
let regex = try NSRegularExpression(pattern: "\\{(\\d+)\\}", options: [])
let matches = regex.matches(in: searchText, options: [], range: NSRange(searchText.startIndex..., in: searchText))
matches.compactMap { Range($0.range(at: 1), in: searchText) }
.forEach { print("Number: \(searchText[$0])") }
Objective-C:
NSString *searchText = #"{53} balloons {12} clowns {123} sparklers";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\d+)\\}"
options:0
error:nil];
NSArray *matches = [regex matchesInString:searchText
options:0
range:NSMakeRange(0, searchText.length)];
for (NSTextCheckingResult *r in matches)
{
NSRange numberRange = [r rangeAtIndex:1];
NSLog(#"Number: %#", [searchText substringWithRange:numberRange]);
}
This will print out:
Number: 53
Number: 12
Number: 123
Try this code.
NSString *myString = #"{53} balloons";
NSString *value = [myString substringWithRange:NSMakeRange(1,2)];
For Swift 2.1 :-
var start = strData?.rangeOfString("{")
var end = strData?.rangeOfString("}")
if (start!.location != NSNotFound && end!.location != NSNotFound && end!.location > start!.location) {
var betweenBraces = strData?.substringWithRange(NSMakeRange(start!.location + 1, end!.location-(start!.location + 1)))
print(betweenBraces)
}
I guess, your a looking for the NSScanner class, at least if you are addressing a general case. Have a look in Apples documentation.
Search the location for "{" and "}".
Take substring between those index.
Checked with any number of data:
NSString *str = #"{53} balloons";
NSArray* strary = [str componentsSeparatedByString: #"}"];
NSString* str1 = [strary objectAtIndex: 0];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSLog(#"number = %#",str2);
Another method is
NSString *tmpStr = #"{53} balloons";
NSRange r1 = [tmpStr rangeOfString:#"{"];
NSRange r2 = [tmpStr rangeOfString:#"}"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *subString = [tmpStr substringWithRange:rSub];
If you don't know how many digits there will be, but you know it will always be enclosed with curly braces try this:
NSString *myString = #"{53} balloons";
NSRange startRange = [myString rangeOfString:#"{"];
NSRange endRange = [myString rangeOfString:#"}"];
if (startRange.location != NSNotFound && endRange.location != NSNotFound && endRange.location > startRange.location) {
NSString *value = [myString substringWithRange:NSMakeRange(startRange.location,endRange.ocation - startRange.location)];
}
There's probably a more efficient way to do it though.

Resources