5

私は、Objective-C を使用した正規表現にはかなり慣れています。私はそれにいくつかの困難を抱えています。

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b([1-9]+)\\b" options:NSRegularExpressionCaseInsensitive error:&regError];
if (regError) {
    NSLog(@"%@",regError.localizedDescription);
}
__block NSString *foundModel = nil;
[regex enumerateMatchesInString:self.model options:kNilOptions range:NSMakeRange(0, [self.model length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
    foundModel = [self.model substringWithRange:[match rangeAtIndex:0]];
    *stop = YES;
}];

私がやろうとしているのは、次のような文字列を取ることだけです

150A

そして得る

150
4

2 に答える 2

8

まず、正規表現の問題:

  1. 単語境界 ( \b) を使用しています。これは、それ自体である数値のみを探していることを意味します (たとえば、15 ではなく 150A)。
  2. あなたの番号範囲には含まれていない0ため、キャプチャされません150。である必要があり[0-9]+、さらに使用する必要があります\d+

したがって、これを修正するには、任意の数をキャプチャする場合に必要なのは\d+. 数字で始まるものをキャプチャしたい場合は、最初に単語境界のみを配置して\b\d+ください。

今すぐ使用できる最初のオカレンスを取得します
-[regex rangeOfFirstMatchInString:options:range:]

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b\\d+" options:NSRegularExpressionCaseInsensitive error:&regError];
if (regError) {
    NSLog(@"%@",regError.localizedDescription);
}

NSString *model = @"150A";
NSString *foundModel = nil;
NSRange range = [regex rangeOfFirstMatchInString:model options:kNilOptions range:NSMakeRange(0, [model length])];
if(range.location != NSNotFound)
{
    foundModel = [model substringWithRange:range];
}

NSLog(@"Model: %@", foundModel);
于 2012-10-26T18:48:27.290 に答える
0

どう.*?(\d+).*?ですか?

デモ: 番号を逆参照し、好きな場所で使用できます。

于 2012-10-26T18:48:07.600 に答える