字符串匹配objective-c

发布于 2024-10-08 09:46:18 字数 100 浏览 7 评论 0原文

我需要以这种方式匹配我的字符串:*myString* 其中 * 表示任何子字符串。 我应该使用哪种方法?

你能帮我吗?

I need to match my string in this way: *myString*
where * mean any substring.
which method should I use?

can you help me, please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拍不死你 2024-10-15 09:46:18

如果适用于 iPhone OS 3.2 或更高版本,请使用 NSRegularExpressionSearch。

NSString *regEx = [NSString stringWithFormat:@".*%@.*", yourSearchString];
NSRange range = [stringToSearch rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {

}

If it's for iPhone OS 3.2 or later, use NSRegularExpressionSearch.

NSString *regEx = [NSString stringWithFormat:@".*%@.*", yourSearchString];
NSRange range = [stringToSearch rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {

}
九公里浅绿 2024-10-15 09:46:18

您无法使用 *(通配符)进行实际搜索,但通常可以执行等效操作:

相当于搜索 theTerm*

if ([theString hasPrefix:@"theTerm"]) {

相当于搜索 *theTerm< /code>:

if ([theString hasSuffix:@"theTerm"]) {

或者,使用如下所示的 NSString 上的类别,以下内容相当于搜索 *theTerm*

if ([theString containsString:@"theTerm"]) {

类别只是一个新方法(就像一个函数) )我们添加到类中。我编写了以下内容,因为对我来说,考虑一个字符串包含另一个字符串比处理 NSRange 更有意义。

// category on NSString
@interface NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString;
@end

@implementation NSString (MDSearchAdditions)

- (BOOL)containsString:(NSString *)aString {
  return [self rangeOfString:aString].location != NSNotFound;
}

@end

You can't do an actual search using a * (wildcard character), but you can usually do something that is equivalent:

Equivalent to searching for theTerm*:

if ([theString hasPrefix:@"theTerm"]) {

Equivalent to searching for *theTerm:

if ([theString hasSuffix:@"theTerm"]) {

Or, using the category on NSString shown below, the following is equivalent to searching for *theTerm*:

if ([theString containsString:@"theTerm"]) {

A category is simply a new method (like a function) that we add to class. I wrote the following one because it generally makes more sense to me to think of one string containing another rather than dealing with NSRanges.

// category on NSString
@interface NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString;
@end

@implementation NSString (MDSearchAdditions)

- (BOOL)containsString:(NSString *)aString {
  return [self rangeOfString:aString].location != NSNotFound;
}

@end
信仰 2024-10-15 09:46:18

如果您需要更先进的东西,请尝试 https://github.com/dblock/objc-ngram

If you need something more evolved, try https://github.com/dblock/objc-ngram.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文