Какое правильное регулярное выражение для поиска определенного шаблона в этих строках?

Итак, у меня есть один большой файл, содержащий кучу данных о погоде. Я должен выделить каждую строку из большого файла в соответствующий файл состояния. Таким образом, всего будет 50 новых файлов состояния со своими данными.

Большой файл содержит примерно 1 миллион строк таких записей:

COOP:166657,'NEW IBERIA AIRPORT ACADIANA REGIONAL LA US',200001,177,553

Хотя название станции может варьироваться и иметь разное количество слов.

Это регулярное выражение, которое я использую:

Pattern p = Pattern.compile(".* ([A-Z][A-Z]) US.*"); 
Matcher m = p.matcher(line);

Когда я запускаю свою программу, все еще есть экземпляры строк, в которых шаблон не может быть найден.

Это моя программа:

package climate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This program will read in a large file containing many stations and states,
 * and output in order the stations to their corresponding state file.
 * 
 * Note: This take a long time depending on processor. It also appends data to
 * the files so you must remove all the state files in the current directory
 * before running for accuracy.
 * 
 * @author Marcus
 *
 */

public class ClimateCleanStates {

    public static void main(String[] args) throws IOException {

        Scanner in = new Scanner(System.in);
        System.out
                .println("Note: This program can take a long time depending on processor.");
        System.out
                .println("It is also not necessary to run as state files are in this directory.");
        System.out
                .println("But if you would like to see how it works, you may continue.");
        System.out.println("Please remove state files before running.");
        System.out.println("\nIs the States directory empty?");
        String answer = in.nextLine();

        if (answer.equals("N")) {
            System.exit(0);
            in.close();
        }
        System.out.println("Would you like to run the program?");
        String answer2 = in.nextLine();
        if (answer2.equals("N")) {
            System.exit(0);
            in.close();
        }

        String[] statesSpaced = new String[51];

        File statefile, dir, infile;

        // Create files for each states
        dir = new File("States");
        dir.mkdir();


        infile = new File("climatedata.csv");
        FileReader fr = new FileReader(infile);
        BufferedReader br = new BufferedReader(fr);

        String line;
        System.out.println();

        // Read in climatedata.csv
        // Probably need to implement ClimateRecord class
        final long start = System.currentTimeMillis();
        while ((line = br.readLine()) != null) {
            // Remove instances of -9999

            if (!line.contains("-9999")) {



                        Pattern p = Pattern.compile("^.* ([A-Z][A-Z]) US.*$"); 
                        Matcher m = p.matcher(line);
                        String stateFileName = null;

                        if(m.find()){
                            //System.out.println(m.group(1));
                            stateFileName = m.group(1);
                        } else {
                            System.out.println("Could not find abbreviation");
                        }

                        /*
                        stateFileName = "States/" + stateFileName + ".csv";
                        statefile = new File(stateFileName);

                        FileWriter stateWriter = new FileWriter(statefile, true);
                        stateWriter.write(line + "\n");
                        // Progress reporting
                        System.out.printf("Writing [%s] to file [%s]\n", line,
                                statefile);
                        stateWriter.flush();
                        stateWriter.close();
                        */





            }
        }
        System.out.println("Elapsed " + (System.currentTimeMillis() - start) + " ms");
        br.close();
        fr.close();
        in.close();

    }

}

person MeesterMarcus    schedule 27.04.2015    source источник
comment
Как я вижу, название станции заключено в одинарные кавычки, почему бы вам просто не искать их пары?   -  person saroff    schedule 28.04.2015
comment
Как оказалось, некоторые строки не содержат аббревиатур штатов.   -  person MeesterMarcus    schedule 28.04.2015
comment
Я бы выводил файлы на основе станции, но они должны быть сгруппированы по состоянию   -  person MeesterMarcus    schedule 28.04.2015


Ответы (5)


Я думаю, вам нужно просмотреть функции, они утверждают, что что-то должно предшествовать или следовать за выражением, которое вы сопоставляете, но не должно быть включено в результат.

(?<= )[A-Z][A-Z](?= US)

(?<= ) должен быть пробел перед

[A-Z][A-Z] ровно две заглавные буквы

(?= US) должен быть пробелом и буквами US после

Возможно, стоит быть более надежным при осмотре: например, (?= US) может быть (?= US',).

person Damian    schedule 28.04.2015

Зависит от того, что вы хотите извлечь точно, но если вы используете шаблон типа

Pattern.compile("(.*):(.*),'(.*)',(.*),(.*),(.*)");
Matcher m = p.matcher(line);
if(m.find()) {
  // here you can use with i from 1 to 6
  m.group(i); 

  //and access the 6 tokens:
  //COOP
  //166657
  //NEW IBERIA AIRPORT ACADIANA REGIONAL LA US
  //200001
  //177
  //553
}
person user1708042    schedule 27.04.2015
comment
Знаете ли вы, есть ли разница в производительности между выполнением разделения и поиском, если строка состоит из двух букв, а не 'US' , или просто выполняете регулярное выражение? Или есть более быстрый способ сделать это? - person MeesterMarcus; 28.04.2015
comment
разделение могло бы быть быстрее, но движок регулярных выражений тоже чертовски быстр: чтобы увидеть разницу, напишите пару тестов на время. Обратите внимание, что вы можете легко отфильтровать свой файл с помощью комбинации инструментов, таких как awk и sed, из командной строки. - person user1708042; 28.04.2015

Вместо

".* ([A-Z][A-Z]) US.*"

если некоторые состояния не сокращены, возможно, попробуйте:

" ([a-z][A-Z])+ US'"

person John McMahon    schedule 27.04.2015

Обратите особое внимание на ^ начало строки, нежадную группу (.*?) , конец строки $, DOTALL и MULTILINE.

Pattern regex = Pattern.compile("^(.*?):(.*?),'(.*?)',(.*?),(.*?),(.*?)$", Pattern.DOTALL | Pattern.MULTILINE);

ДЕМО регулярного выражения:

https://regex101.com/r/bX0rS3/1


Живой пример JAVA:

http://ideone.com/uAUaJT


Объяснение регулярного выражения:

^(.*?):(.*?),'(.*?)',(.*?),(.*?),(.*?)$

Options: Case sensitive; Exact spacing; Dot matches line breaks; ^$ match at line breaks; Default line breaks

Assert position at the beginning of a line (at beginning of the string or after a line break character) (carriage return and line feed, next line, line separator, paragraph separator) «^»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “:” literally «:»
Match the regex below and capture its match into backreference number 2 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “,'” literally «,'»
Match the regex below and capture its match into backreference number 3 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “',” literally «',»
Match the regex below and capture its match into backreference number 4 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “,” literally «,»
Match the regex below and capture its match into backreference number 5 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “,” literally «,»
Match the regex below and capture its match into backreference number 6 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) (carriage return and line feed, next line, line separator, paragraph separator) «$»
person Pedro Lobito    schedule 27.04.2015

Вы можете подтвердить, что это аббревиатура штата США:

\s(?:(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])(?:\sUS'|'))

Демо

person dawg    schedule 28.04.2015