问题描述
我正在尝试解析一个字符串并在中间获得另一个字符串。
I am trying to parse a string and get another string in the middle.
ie。
Hello world这是一个字符串
Hello world this is a string
我需要找到world和is之间的字符串(这个)。我环顾四周但还未能弄清楚,主要是因为我是Objective C的新手...任何人都知道如何使用RegEx或不使用它?
I need to find the string between "world" and "is" (this). I have looked around but haven't been able to figure it out yet, mainly because I am new to Objective C... Anyone have an idea of how to do this, with RegEx or without?
推荐答案
Jacques提供的正则表达式解决方案,以及要求iOS 4.0及更高版本的警告是正确的。使用正则表达式也很慢,如果搜索表达式是已知的字符串常量,那就太过分了。
The regular expressions solution that Jacques gives works, and the caveat of requiring iOS 4.0 and later is true. Using regular expressions is also quite slow, and an overkill if the search expressions are known string constants.
您可以使用 NSString
上的方法或名为 NSScanner ,自从iPhone OS 2.0开始以及很久以前就已经可用,因为在Mac OS X 10.0实际上之前:)。
You can solve the problem using methods on NSString
, or a class named NSScanner
, both have been available since iPhone OS 2.0 and long before that, since before Mac OS X 10.0 actually :).
所以你想要的是一个关于 NSString
的新方法是这样的?
So what you want is a new method on NSString
like this?
@interface NSString (CWAddition)
- (NSString*) stringBetweenString:(NSString*)start andString:(NSString*)end;
@end
没问题,我们假设我们应该返回 nil
是不能找到这样的字符串。
No problem, and we assume we should return nil
is no such strings could be found.
仅使用 NSString
的实现是非常直接:
The implementation using NSString
only is quite straight forward:
@implementation NSString (NSAddition)
- (NSString*) stringBetweenString:(NSString*)start andString:(NSString*)end {
NSRange startRange = [self rangeOfString:start];
if (startRange.location != NSNotFound) {
NSRange targetRange;
targetRange.location = startRange.location + startRange.length;
targetRange.length = [self length] - targetRange.location;
NSRange endRange = [self rangeOfString:end options:0 range:targetRange];
if (endRange.location != NSNotFound) {
targetRange.length = endRange.location - targetRange.location;
return [self substringWithRange:targetRange];
}
}
return nil;
}
@end
或者您可以使用<$执行实施c $ c> NSScanner class:
Or you could do the implementation using the NSScanner
class:
@implementation NSString (NSAddition)
- (NSString*) stringBetweenString:(NSString*)start andString:(NSString*)end {
NSScanner* scanner = [NSScanner scannerWithString:self];
[scanner setCharactersToBeSkipped:nil];
[scanner scanUpToString:start intoString:NULL];
if ([scanner scanString:start intoString:NULL]) {
NSString* result = nil;
if ([scanner scanUpToString:end intoString:&result]) {
return result;
}
}
return nil;
}
@end
这篇关于在ObjC中获取两个其他字符串之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!