我有一个像ConsumerVisit(201)或Date(CX1)这样的字符串。如何在括号“(”“)”中得到字符串?
我尝试了几次以下代码,但它在substringWithRange中崩溃了。
NSRange match;
NSRange match1;
match = [_actType.text rangeOfString: @"("];
match1 = [_actType.text rangeOfString: @")"];
NSLog(@"%i,%i",match.location,match1.location);
NSString *newDes = [_actType.text substringWithRange: NSMakeRange (match.location, match1.location-1)];
答案 0 :(得分:1)
尝试下面的代码..
NSString *newDes = _actType.text;
NSArray *strArray = [newDes componentsSeparatedByString:@"("];
newDes = [strArray objectAtIndex:1];
strArray = [newDes componentsSeparatedByString:@")"];
newDes = [strArray objectAtIndex:0];
newDes的值应为 201 ..
我和你的价值一样使用贝娄..
NSString *newDes = @"ConsumerVisit(201)";
NSArray *strArray = [newDes componentsSeparatedByString:@"("];
newDes = [strArray objectAtIndex:1];
strArray = [newDes componentsSeparatedByString:@")"];
newDes = [strArray objectAtIndex:0];
NSLog(@"\n\n newDes ==>> %@",newDes);
退出是 newDes ==>> 201 强>
答案 1 :(得分:1)
使用以下代码
NSString *subString = nil;
NSString * myString = @" hello(1234)";
NSRange range1 = [myString rangeOfString:@"("];
NSRange range2 = [myString rangeOfString:@")"];
if ((range1.length == 1) && (range2.length == 1) && (range2.location > range1.location))
{
NSRange range3;
range3.location = range1.location+1;
range3.length = (range2.location - range1.location)-1;
subString = [myString substringWithRange:range3];
}
NSLog(@"%@",subString);
输出=====> 1234 强>
答案 2 :(得分:1)
如果您有足够的冒险精神,可以使用实际上为此目的创建的正则表达式。不过,他们确实需要一点点习惯。
NSString *text = @"ConsumerVisit(201)";
NSString *substring = nil;
NSRange parenRng = [text rangeOfString: @"(?<=\\().*?(?=\\))" options: NSRegularExpressionSearch];
if ( parenRng.location != NSNotFound ) {
substring = [text substringWithRange:parenRng];
}
模式如下所示:
\\(
(?<=)
构造表示。这被称为积极的后视。答案 3 :(得分:0)
我想出来了..
NSString *originalString = @"ConsumerVisit(201)"
NSRange start = [originalString rangeOfString:@"("];
NSRange end = [originalString rangeOfString:@")"];
NSString *betweenBraces;
if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location) {
betweenBraces = [originalString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
}
NSLog(@"Sub string: %@", betweenBraces);
输出&GT;子字符串:201
感谢@paras n @vinu的快速回答。