Разделение найденных совпадений на отдельные группы - PullRequest
1 голос
/ 22 февраля 2020

Привет. У меня возникли проблемы при попытке сопоставить выбранный текст с помощью Matcher. Позвольте мне объяснить с некоторыми примерами:

Вот текст, который я просматриваю: (Если это поможет, я сгенерировал это из некоторого XML, поэтому исходные данные выглядели не так, как я. надо работать с)

__ELEMENT: question
____Text: (a) Look at the following:
__ELEMENT: maths
____Text: x
__ELEMENT: maths
____Text: x^2
__ELEMENT: maths
____Text: x^3
__ELEMENT: question
____Text: Then do this blah blah blah.
__ELEMENT: question
____Text: (b) Hence do the other thing blah blah blah.
__ELEMENT: maths
____Text: x^4
__ELEMENT: maths
____Text: x^5

Поэтому я пытаюсь найти текст, следующий за «вопросом» и всеми последующими математическими элементами; Я имею в виду, что я хотел бы получить:

(a) Look at the following:
x x^2 x^3
Then do this blah blah blah.
(b) Hence do the other thing blah blah blah.
x^4 x^5

Но все, что я пробовал до сих пор, только что дало бесполезные вещи, как:

(a) Look at the following:
x x^2 x^3 x^4 x^5
Then do this blah blah blah.
(b) Hence do the other thing blah blah blah.
x x^2 x^3 x^4 x^5

Или хуже

Вот соответствующий бит кода:

    string text = "__ELEMENT: question\n" +
"____Text: (a) Look at the following:\n" +
"__ELEMENT: maths\n" +
"____Text: x\n" +
"__ELEMENT: maths\n" +
"____Text: x^2\n" +
"__ELEMENT: maths\n" +
"____Text: x^3\n" +
"__ELEMENT: question\n" +
"____Text: Then do this blah blah blah.\n" +
"__ELEMENT: question\n" +
"____Text: (b) Hence do the other thing blah blah blah.\n" +
"__ELEMENT: maths\n" +
"____Text: x^4\n" +
"__ELEMENT: maths\n" +
"____Text: x^5";
    Pattern p = Pattern.compile("(?<=question\\n.*Text:).+");
    Matcher m = p.matcher(text);
    if (m.find()) {
    String findQuestion = m.group(0);
    String newQuestion = findQuestion;
    while (m.find()) {
                Pattern pat = Pattern.compile("maths\\n_*Text: (.*(?:\\n(?!_*ELEMENT).*)*)\\n");
    Matcher mat = pat.matcher(text);
    if (mat.find()) {
    String findMath = mat.group(1);
    String newMath = findEquationQ;
    while (mat.find()) {
        newQuestion += mat.group(1);
    }
    finalMatches.add(newQuestion);
    }
    }
    //      finalMatches.add(newQuestion);
    }

Да, это беспорядок

Любая помощь будет оценена Или просто какой-нибудь лог c или псевдокод, чтобы помочь

1 Ответ

1 голос
/ 23 февраля 2020

Вы имеете в виду что-то подобное?

static void parseQuestionAndMaths(String input) {
    Pattern p = Pattern.compile("\\G__ELEMENT:\\h*(question|maths)\\h*\\R" +
                                   "____Text:\\h*(.*)\\R?");
    int end = 0;
    String question = null;
    List<String> maths = new ArrayList<>();
    for (Matcher m = p.matcher(input); m.find(); end = m.end()) {
        if (m.group(1).equals("maths")) {
            maths.add(m.group(2).trim());
        } else {
            if (question != null)
                printQuestionAndMaths(question, maths);
            question = m.group(2);
            maths.clear();
        }
    }
    if (question != null)
        printQuestionAndMaths(question, maths);
    if (end < input.length()) {
        throw new IllegalArgumentException("Unexpected text at offset " + end + ": " +
                         input.substring(end).replaceFirst("(.*\\R.*)(?s:.*)", "$1"));
    }
}

private static void printQuestionAndMaths(String question, List<String> maths) {
    System.out.println("Q: " + question);
    if (! maths.isEmpty())
        System.out.println("M: " + maths.stream().collect(Collectors.joining(" ")));
}

Тест

String input = "__ELEMENT: question\n" + 
               "____Text: (a) Look at the following:\n" + 
               "__ELEMENT: maths\n" + 
               "____Text: x\n" + 
               "__ELEMENT: maths\n" + 
               "____Text: x^2\n" + 
               "__ELEMENT: maths\n" + 
               "____Text: x^3\n" + 
               "__ELEMENT: question\n" + 
               "____Text: Then do this blah blah blah.\n" + 
               "__ELEMENT: question\n" + 
               "____Text: (b) Hence do the other thing blah blah blah.\n" + 
               "__ELEMENT: maths\n" + 
               "____Text: x^4\n" + 
               "__ELEMENT: maths\n" + 
               "____Text: x^5";
parseQuestionAndMaths(input);

Выход

Q: (a) Look at the following:
M: x x^2 x^3
Q: Then do this blah blah blah.
Q: (b) Hence do the other thing blah blah blah.
M: x^4 x^5
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...