How do I get the substring between braces?

2019-05-02 10:02发布

问题:

I have a string as this.

NSString *myString = @"{53} balloons";

How do I get the substring 53 ?

回答1:

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.



回答2:

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.



回答3:

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


回答4:

Try this code.

 NSString *myString = @"{53} balloons";
 NSString *value = [myString substringWithRange:NSMakeRange(1,2)];


回答5:

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)
}


回答6:

I guess, your a looking for the NSScanner class, at least if you are addressing a general case. Have a look in Apples documentation.



回答7:

Search the location for "{" and "}". Take substring between those index.



回答8:

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];


回答9:

For Swift 4.2:

if let r1 = string.range(of: "{")?.upperBound,
let r2 = string.range(of: "}")?.lowerBound {
    print (String(string[r1..<r2]))
}


回答10:

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.