[英]Getting NSRange of string between quotations?
I have a string: 我有一个字符串:
He said "hello mate" yesterday.
他昨天说“你好伙计”。
I want to get an NSRange from the first quotation to the last quotation. 我想从第一个报价到最后一个报价获得NSRange。 So I tried something like this:
所以我尝试过这样的事情:
NSRange openingRange = [title rangeOfString:@"\""];
NSRange closingRange = [title rangeOfString:@"\""];
NSRange textRange = NSMakeRange(openingRange.location, closingRange.location+1 - openingRange.location);
But I'm not sure how to make it distinguish between the first quote and the second quote. 但我不确定如何区分第一个引用和第二个引用。 How would I do this?
我该怎么做?
You could use a regular expression for this: 您可以使用正则表达式:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([\"])(?:\\\\\\1|.)*?\\1" options:0 error:&error];
NSRange range = [regex rangeOfFirstMatchInString:myString options:0 range:NSRangeMake(0, [myString length]];
Don't forget to check for errors ;) 不要忘记检查错误;)
You can always use 'rangeOfString:options:range:' for the second one (starting after the 'location' of the first one). 您可以随时使用'rangeOfString:options:range:'作为第二个(从第一个的'location'开始)。
Option 1 选项1
- (NSRange)rangeOfQuoteInString:(NSString *)str {
int firstMatch = [str rangeOfString:@"\""].location;
int secondMatch = [str rangeOfString:@"\"" options:0 range:NSMakeRange(firstMatch + 1, [str length] - firstMatch - 1)].location;
return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}
I hope this is right. 我希望这是对的。 Done on my phone at dinner.
晚餐时在我的手机上完成。 ;-)
;-)
One other thing, though, since range of string likely does a similar implementation, why not iterate the 'char' values in the string and look for matches #1 & #2? 另外一件事,因为字符串的范围可能会执行类似的实现,为什么不迭代字符串中的'char'值并查找匹配#1和#2? Could be as fast or faster.
可以快速或更快。
Option 2 选项2
- (NSRange)rangeOfQuoteInString:(NSString *)str {
int firstMatch = -1;
int secondMatch = -1;
for (int i = 0; i < [str length]; i = i + 1) {
unichar c = [str characterAtIndex:i];
if (c == '"') {
if (firstMatch == -1) {
firstMatch = i;
} else {
secondMatch = i;
break;
}
}
}
if (firstMatch == -1 || secondMatch == -1) {
// No full quote was found
return NSMakeRange(NSNotFound, 0);
} else {
return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.