簡體   English   中英

在字符串中查找數字模式

[英]Find number pattern in string

我希望能夠在刺痛中找到一個子串,但它有一個獨特的模式,我不知道如何找到。

EX。

NSString *test1= @"Contact Names
                  67-444-322
                  Dec 21 2012
                  23941 6745 9145072 01567
                  5511 23345 614567 123456
                  Older Contacts
                  See Back Side";

我想在子字符串中找到以下模式(這些數字但不是日期數字)

                  23941 6745 9145072 01567
                  5511 23345 614567 123456

但是,示例字符串的格式幾乎不會相同。 除了“聯系人姓名”,“舊聯系人”和“查看背面”之外,每次都會有不同的號碼和不同的標題。 一個將保持不變的是我正在尋找的數字總是有4個數字,但可能有1行或10行。

有誰知道我會如何解決這個問題? 我正在考慮的事情可能只是找到字符串中的數字,然后檢查哪些數字之間有3個空格。

謝謝

我嘗試過以下內容並且有效:

NSString *test1= @"Contact Names\n"
    "67-444-322\n"
    "Dec 21 2012\n"
    "23941 6745 9145072 01567\n"
    "5511 23345 614567 123456\n"
    "Older Contacts\n"
    "See Back Side";

NSString *pattern = @"(([0-9]+ ){3}+[0-9]+)(\\n(([0-9]+ ){3}+[0-9]+))*";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSArray *results = [regex matchesInString:test1 options:0 range:NSMakeRange(0, [test1 length])];
if ([results count] > 0) {
    NSTextCheckingResult *result = [results objectAtIndex:0];
    NSString *match = [test1 substringWithRange:result.range];
    NSLog(@"\n%@", match); // These are your numbers
}

(如果只有一行數字,它也可以工作。)

您可以使用字符集來分隔字符串,然后確定每個組件中是否有4個數字。 這只有在字符串中有換行符( \\n )時才會起作用(因為你對Lance的回應似乎表明)。

我就是這樣做的:

NSString *test1= @"Contact Names\n
              67-444-322\n
              Dec 21 2012\n
              23941 6745 9145072 01567\n
              5511 23345 614567 123456\n
              Older Contacts\n
              See Back Side";

NSArray *lines = [test1 componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet];

// lines now contains each line in test1

for (NSString* line in lines) {

    NSArray *elements = [line componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet];

    if (elements.count == 4) {
        // This line contains 4 numbers
        // convert each number string into an int if needed
    }
}

對於長代碼行感到抱歉,Apple的一些選擇器有點偏長......無論如何,如果元素有4個單獨的( NSString )對象,那么它就是你正在尋找的行之一,你可以操縱它您需要的數據。

編輯(旁邊):

關於regex表達式的主題(因為這個問題包含regex標記),是的,你可以使用正則表達式,但是Objective-C並沒有真正有一種處理它們的“好方法”...正則表達式更多的是在腳本編寫領域語言和語言,內置支持它。

我改進了我的代碼以使其更具可讀性並在找到字符串時停止(不會破壞行...如果你需要這個也告訴我再次添加代碼或者如果有困難就幫助你)

我使用的正則表達式是:
- 一個或多個數字后跟一個或多個空格(樹時間全部)
- 一個或多個數字后跟一個或多個空格(這些是行更改,制表符,空格等)
- 我試圖找到這整個模式重復一次或多次

代碼是

NSString *test1= @"Contact Names\n    67-444-322\n\nDec 21 2012\n23941 6745 9145072 01567\n5511 23345 614567 123456\nOlder Contacts\nSee Back Side\n";

//create the reg expr
NSString *pattern1 = @"(([0-9]+ +){3}[0-9]+\\s+)+";
NSRegularExpression *regex1 = [NSRegularExpression regularExpressionWithPattern:pattern1 options:0 error:nil];
//find matches
NSArray *results1 = [regex1 matchesInString:test1 options:0 range:NSMakeRange(0, [test1 length])];
if ([results1 count] > 0) {
    //if i find more series...what should i do?
    if ([results1 count] > 1) {
        NSLog(@"I found more than one matching series....what should i do?!");
        exit(111);
    }
    //find series and print
    NSTextCheckingResult *resultLocation1 = [results1 objectAtIndex:0];
    NSString *match1 = [test1 substringWithRange:resultLocation1.range];
    //trim leading and ending whitespaces
    match1=[match1 stringByTrimmingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"the series is \n%@", match1);        
}else{
    NSLog(@"No matches found in string");
}

希望能幫助到你

#include <stdio.h>
#include <string.h>
#include <pcre.h>

int main(int argc, char **argv)
{
  const char *error;
  int erroffset;
  int ovector[186];
  char re[8192]="";
  char txt[]="Dec 21 2012                   23941 6745 9145072 01567                   5511 23345 614567 123456                   Ol\";";

  char re1[]=".*?"; // Non-greedy match on filler
  strcat(re,re1);
  char re2[]="\\d+";    // Uninteresting: int
  strcat(re,re2);
  char re3[]=".*?"; // Non-greedy match on filler
  strcat(re,re3);
  char re4[]="\\d+";    // Uninteresting: int
  strcat(re,re4);
  char re5[]=".*?"; // Non-greedy match on filler
  strcat(re,re5);
  char re6[]="(\\d+)";  // Integer Number 1
  strcat(re,re6);
  char re7[]="(\\s+)";  // White Space 1
  strcat(re,re7);
  char re8[]="(\\d+)";  // Integer Number 2
  strcat(re,re8);
  char re9[]="(\\s+)";  // White Space 2
  strcat(re,re9);
  char re10[]="(\\d+)"; // Integer Number 3
  strcat(re,re10);
  char re11[]="(\\s+)"; // White Space 3
  strcat(re,re11);
  char re12[]="(\\d+)"; // Integer Number 4
  strcat(re,re12);
  char re13[]="(\\s+)"; // White Space 4
  strcat(re,re13);
  char re14[]="(\\d+)"; // Integer Number 5
  strcat(re,re14);
  char re15[]="(\\s+)"; // White Space 5
  strcat(re,re15);
  strcat(re,re16);
  char re17[]="(\\s+)"; // White Space 6
   strcat(re,re17);
  char re18[]="(\\d+)"; // Integer Number 7
  strcat(re,re18);
  char re19[]=".*?";    // Non-greedy match on filler
  strcat(re,re19);
  char re20[]="(\\d+)"; // Integer Number 8
  strcat(re,re20);

  pcre *r =  pcre_compile(re, PCRE_CASELESS|PCRE_DOTALL, &error, &erroffset, NULL);
  int rc = pcre_exec(r, NULL, txt, strlen(txt), 0, 0, ovector, 186);
  if (rc>0)
 {
  char int1[1024];
  pcre_copy_substring(txt, ovector, rc,1,int1, 1024);
  printf("(%s)",int1);
  char ws1[1024];
  pcre_copy_substring(txt, ovector, rc,2,ws1, 1024);
  printf("(%s)",ws1);
  char int2[1024];
  pcre_copy_substring(txt, ovector, rc,3,int2, 1024);
  printf("(%s)",int2);
  char ws2[1024];
  pcre_copy_substring(txt, ovector, rc,4,ws2, 1024);
  printf("(%s)",ws2);
  char int3[1024];
  pcre_copy_substring(txt, ovector, rc,5,int3, 1024);
  printf("(%s)",int3);
  char ws3[1024];
  pcre_copy_substring(txt, ovector, rc,6,ws3, 1024);
  printf("(%s)",ws3);
  char int4[1024];
  pcre_copy_substring(txt, ovector, rc,7,int4, 1024);
  printf("(%s)",int4);
  char ws4[1024];
  pcre_copy_substring(txt, ovector, rc,8,ws4, 1024);
  printf("(%s)",ws4);
  char int5[1024];
  pcre_copy_substring(txt, ovector, rc,9,int5, 1024);
  printf("(%s)",int5);
  char ws5[1024];
  pcre_copy_substring(txt, ovector, rc,10,ws5, 1024);
  printf("(%s)",ws5);
  char int6[1024];
  pcre_copy_substring(txt, ovector, rc,11,int6, 1024);
  printf("(%s)",int6);
  char ws6[1024];
  pcre_copy_substring(txt, ovector, rc,12,ws6, 1024);
  printf("(%s)",ws6);
  char int7[1024];
  pcre_copy_substring(txt, ovector, rc,13,int7, 1024);
  printf("(%s)",int7);
  char int8[1024];
  pcre_copy_substring(txt, ovector, rc,14,int8, 1024);
  printf("(%s)",int8);
  puts("\n");
  }
}

從下次使用http://txt2re.com

你也可以制作一個簡單的正則表達式。 為此,您只能在1個char變量中編寫它們。

創建一個數組,其中包含所有月份的名稱,例如monthArray。

然后使用空格分割整個字符串。 現在在for循環檢查中

if(分割數組的四個連續元素是數字)

  {

 if(previous 5th, 6th and seventh element in the splited array does not belong to monthArray)//if forloop count is 7 then previous 5th means the 2nd element in the splited array
     {
       those 4 consecutive variable belongs to a row you are looking for.

      }
   }

// ------------------------------------------------ ----------

NSArray *monthArray = [[NSArray alloc] initWithObjects:@"Dec", nil];//here you have to add the 12 monts name. Now i added only 'Dec'
NSString *test1= @"Contact Names 67-444-322 Dec 21 2012 23941 6745 9145072 01567 5511 23345 614567 123456 Older Contacts See Back Side";
NSArray *splitArray = [test1 componentsSeparatedByString:@" "];
int count = 0;

for (int i =0; i<splitArray.count; i++) {
    if ([[[splitArray objectAtIndex:i] componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] count]==1)//checks if it is a pure integer
    {
        count ++;
    }else count= 0;

    if (count>=4) {
        if (i-4>=0) {
            if ([monthArray containsObject:[splitArray objectAtIndex:i-4]]) {
                continue;
            }
        }
        if (i-5>=0) {
            if ([monthArray containsObject:[splitArray objectAtIndex:i-5]]) {
                continue;
            }
        }
        NSLog(@"myneededRow===%@ %@ %@ %@",[splitArray objectAtIndex:i-3],[splitArray objectAtIndex:i-2],[splitArray objectAtIndex:i-1],[splitArray objectAtIndex:i]);
        count = 0;

    }
}

如果數字的數量永遠不會改變,即[5個數字] [空格] [4個數字] [空格] ......

然后,您可以使用NSRegularExpression設置模式,然后在字符串中搜索模式。

https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

試試NSLingustic Tagger課程。

NSMutableArray numbers = [NSMutableArray new];
NSString *test1= @"Contact Names
                      67-444-322
                      Dec 21 2012
                      23941 6745 9145072 01567
                      5511 23345 614567 123456
                      Older Contacts
                      See Back Side";
    NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames;
    NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes: [NSLinguisticTagger availableTagSchemesForLanguage:@"en"] options:options];
    tagger.string = test1;
    [tagger enumerateTagsInRange:NSMakeRange(0, [test1 length]) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:options usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
        NSString *token = [test1 substringWithRange:tokenRange];
        if(Tag == NSLinguisticTagNumber){
           [numbers addObject:token];
        }
    }];
NSLogs("All Numbers in my strings are: %@", numbers);

這應該工作。 我不得不在你的輸入中添加換行符以使我的工作正常工作,但我假設你從API或文件中獲取字符串,所以它應該已經有新行。

NSString *test1= @"Contact Names\
    67-444-322\n\
    Dec 21 2012\n\
    23941 6745 9145072 01567\n\
    5511 23345 614567 123456\n\
    Older Contacts\n\
    See Back Side";

    // first, separate by new line
    NSArray* allLinedStrings =
    [test1 componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"^[0-9 ]+$"
                                                                      options:0
                                                                        error:nil];
    for (NSString *line in allLinedStrings) {
        NSArray *matches = [regex matchesInString:line options:0 range:NSMakeRange(0, [line length])];
        if (matches.count) {
            NSTextCheckingResult *result = matches[0];
            NSString *match = [line substringWithRange:result.range];
            NSLog(@"match found: %@\n", match);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM