1

iphoneアプリを作っています。大量のデータを含む巨大な文字列があり、文字列から電子メール アドレスのみを抽出したいというシナリオがあります。

たとえば、文字列が次のような場合

asdjasjkdh asdhajksdh jkashd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com

「sample@email.com」と「test@gmail.com」を抽出する必要があります

また、文字列から日付のみを抽出したい

たとえば、文字列が次のような場合

asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com

「2012 年 1 月 1 日」と「2012 年 12 月 11 日」を抽出する必要があります。

小さなコード スニペットが非常に役立ちます。

前もって感謝します

4

3 に答える 3

10

これはあなたが望むことをします:

// regex string for emails (feel free to use a different one if you prefer)
NSString *regexString = @"([A-Za-z0-9_\\-\\.\\+])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]+)";

// experimental search string containing emails
NSString *searchString = @"asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com";

// track regex error
NSError *error = NULL;

// create regular expression
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:&error];

// make sure there is no error
if (!error) {

    // get all matches for regex
    NSArray *matches = [regex matchesInString:searchString options:0 range:NSMakeRange(0, searchString.length)];

    // loop through regex matches
    for (NSTextCheckingResult *match in matches) {

        // get the current text
        NSString *matchText = [searchString substringWithRange:match.range];

        NSLog(@"Extracted: %@", matchText);

    }

}

上記のサンプル文字列を使用する:

asdjasjkdh2012年1月1日asdhajksdhjkas2012年11月12日hdsample@email.comasdha jksdh asjdhjak sdkajs test@gmail.com

出力は次のとおりです。

Extracted: sample@email.com
Extracted: test@gmail.com

コードを使用するには、searchString検索する文字列に設定するだけです。NSLog()メソッドの代わりに、抽出された文字列を使用して何かを実行することをお勧めしますmatchText。別の正規表現文字列を使用してメールを抽出regexStringしてください。コード内のの値を置き換えるだけです。

于 2012-12-12T03:42:10.057 に答える
1
NSArray *chunks = [mylongstring componentsSeparatedByString: @" "];

for(int i=0;i<[chunks count];i++){
    NSRange aRange = [chunks[i] rangeOfString:@"@"];
    if (aRange.location !=NSNotFound) NSLog(@"email %@",chunks[i] );
}
于 2012-11-08T14:17:18.670 に答える
0

この正規表現を使用してメールを照合できます

 [^\s]*@[^\s]*

日付を一致させるためのこの正規表現

 \d+/\d+/\d+
于 2012-11-08T12:47:07.863 に答える