How do I get the substring between braces? - ios

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.

Related

How to parse a NSString

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

Finding word in NSString and checking before and after character this word?

How to find word in NSString and check characters before and after this word?
"This pattern has two parts separated by the"
How to find tern and how to check the character before and after
Before word character:"t"
After word character:" "
You can use NSScanner to get indexes of these two characters.
Example:
NSString *string = #"tern";
NSScanner *scanner = [[NSScanner alloc] initWithString:#"This pattern has two parts separated by the"];
[scanner scanUpToString:string intoString:nil];
NSUInteger indexOfChar1 = scanner.scanLocation - 1;
NSUInteger indexOfChar2 = scanner.scanLocation + string.length;
You can also use a rangeOfString method:
Example:
NSRange range = [sourceString rangeOfString:stringToLookFor];
NSUInteger indexOfChar1 = range.location - 1;
NSUInteger indexOfChar2 = range.location +range.length + 1;
Then, when you have indexes, getting the characters is easy:
NSString *firstCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar1, 1)];
NSString *secondCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar2, 1)];
Hope this helps.
Here is an implementation using Regular Expressions
NSString *testString= #"This pattern has two parts separated by the";
NSString *regexString = #"(.)(tern)(.)";
NSRegularExpression* exp = [NSRegularExpression
regularExpressionWithPattern:regexString
options:NSRegularExpressionSearch error:&error];
if (error) {
NSLog(#"%#", error);
} else {
NSTextCheckingResult* result = [exp firstMatchInString:testString options:0 range:NSMakeRange(0, [testString length] ) ];
if (result) {
NSRange groupOne = [result rangeAtIndex:1]; // 0 is the WHOLE string.
NSRange groupTwo = [result rangeAtIndex:2];
NSRange groupThree = [result rangeAtIndex:3];
NSLog(#"[%#][%#][%#]",
[testString substringWithRange:groupOne],
[testString substringWithRange:groupTwo],
[testString substringWithRange:groupThree] );
}
}
Results:
[t][tern][ ]
Its better to get pre and post character in NSString to avoid handling of unicode characters.
NSString * testString = #"This pattern has two parts separated by the";
NSString * preString;
NSString * postString;
NSUInteger maxRange;
NSRange range = [testString rangeOfString:#"tern"];
if(range.location == NSNotFound){
NSLog(#"Not found");
return;
}
if (range.location==0) {
preString=nil;
}
else{
preString = [testString substringWithRange:NSMakeRange(range.location-1,1)];
}
maxRange = NSMaxRange(range);
if ( maxRange >=testString.length ) {
postString = nil;
}
else{
postString = [testString substringWithRange:NSMakeRange(range.location+range.length, 1)];
}

NSString substring between predefined strings

How can I get a substring between predefined strings. For example:
NSString* sentence = #"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = #"{start}";
NSString* end = #"{end}";
NSString* myWord = [do some stuff with:sentence and:start and:end];
NSLog(#"myWord - %#",myWord);
Log: myWord - this
The following will give you the output you want:
NSString* sentence = #"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = #"{start}";
NSString* end = #"{end}";
NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];
if (startRange.location != NSNotFound && endRange.location != NSNotFound) {
NSString *myWord = [sentence substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length)];
NSLog(#"myWord - %#", myWord);
}
else {
NSLog(#"myWord not found");
}
You can use rangeOfString:to get the location of each of the markers. Then use subStringWithRange:to extract the string part you want.
NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence end];
NSString myWord = [NSString subStringWithRange:NSMakeRange(startRange.location+startRange.length, endRange.location-startRange.location+startRange.length)];
All code typed in Safari and no error handling included!
NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];
int startLocation = startRange.location + startRange.length;
int lenght = endRange.location - startLocation;
NSString* myWord = [sentence substringWithRange:NSMakeRange(startLocation, lenght)];

Remove all non-numeric characters from an NSString, keeping spaces

I am trying to remove all of the non-numeric characters from an NSString, but I also need to keep the spaces. Here is what I have been using.
NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];
If I give it a NSString of Test 333 9599 999 It will return 3339599999 but I need to keep the spaces in.
How can I do this?
Easily done by creating a character set of characters you want to keep and using invertedSet to create an "all others" set. Then split the string into an array separated by any characters in this set and reassemble the string again. Sounds complicated but very simple to implement:
NSCharacterSet *setToRemove =
[NSCharacterSet characterSetWithCharactersInString:#"0123456789 "];
NSCharacterSet *setToKeep = [setToRemove invertedSet];
NSString *newString =
[[someString componentsSeparatedByCharactersInSet:setToKeep]
componentsJoinedByString:#""];
result: 333 9599 99
You could alter your first regex to include a space after the 9:
In swift:
var str = "test Test 333 9599 999";
val strippedStr = str.stringByReplacingOccurrencesOfString("[^0-9 ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
// strippedStr = " 33 9599 999"
While this leaves the leading space, you could apply a whitespace trimming to deal with that:
strippedStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// strippedStr = "33 9599 999"
// Our test string
NSString* _bbox = #"Test 333 9599 999";
// Remove everything except numeric digits and spaces
NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:#"[^\\d ]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];
// (Optional) Trim spaces on either end, but keep spaces in the middle
strippedBbox = [strippedBbox stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// Print result
NSLog(#"%#", strippedBbox);
This prints 333 9599 999, which I think is what you're after. It also removes non numeric characters that may be in the middle of the string, such as parentheses.
For Swift 3.0.1 folks
var str = "1 3 6 .599.188-99 "
str.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression, range: nil)
Output: "13659918899"
This also trim spaces from string
try using NSScanner
NSString *originalString = #"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789 "];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString); // "123123123"
NSMutableString strippedBbox = [_bbox mutableCopy];
NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:#"1234567890 "].invertedSet;
NSUInteger start = 0;
NSUInteger length = _bbox.length;
while(length > 0)
{
NSRange range = [strippedBbox rangeOfCharacterFromSet:charSet options:0 range:NSMakeRange(start, length)];
if(range.location == NSNotFound)
{
break;
}
start += (range.location + range.length);
length -= range.length;
[strippedBbox replaceCharactersInRange:range withString:#""];
}
In brief, you can use NSCharacterSet to examine only those chars that are interesting to you and ignore the rest.
- (void) stripper {
NSString *inString = #"A1 B2 C3 D4";
NSString *outString = #"";
for (int i = 0; i < inString.length; i++) {
if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:[inString characterAtIndex:i]] || [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[inString characterAtIndex:i]]) {
outString = [outString stringByAppendingString:[NSString stringWithFormat:#"%c",[inString characterAtIndex:i]]];
}
}
}

iOS : Get substring from a html tag response

In my program I'm getting an html notification tag use
"<script>p(34,'1','hello world');</script>/r/n"
I need now is to get the string "hello world" from above tag and it should be a dynamic process as the length of text varies for every response tag.
Something like this will work. You may have to adjust the fromString and toString if those parts of the message are also dynamic, but this will get you started.
NSString *someString = #"<script>p(34,'1','hello world');</script>/r/n";
NSString *fromString = #"<script>p(34,'1','";
NSRange fromRange = [someString rangeOfString:fromString];
NSString *toString = #"');</script>/r/n";
NSRange toRange = [someString rangeOfString:toString];
NSRange range = NSMakeRange(fromRange.location + fromRange.length, toRange.location - (fromRange.location + fromRange.length));
NSString *result = [someString substringWithRange:range];
Please try to use this one.... I Hope this work will fine..
NSString *data = #"<script>p(34,'1','hello world');</script>/r/n";
NSRange divRange = [data rangeOfString:#"','" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [data length] - endDivRange.location;
endDivRange = [data rangeOfString:#"'" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
NSLog(#"SubString %#",[data substringWithRange:divRange]);
}
}
NSString * myString = #"<script>p(34,'1','hello world');</script>/r/n";//#" hello(1234)";
NSRange range1 = [myString rangeOfString:#"," options:NSBackwardsSearch];
NSRange range2 = [myString rangeOfString:#"'" options:NSBackwardsSearch];
if ((range1.length == 1) && (range2.length == 1) && (range2.location > range1.location))
{
NSRange range3;
range3.location = range1.location+2;
range3.length = (range2.location - range1.location)-2;
NSString *subString = [myString substringWithRange:range3];
NSLog(#"%#",subString)
}
outPut----> hello world

Resources