Манипулирование строками в java

#java

#java

Вопрос:

У меня есть многострочная строка, как показано ниже, я хочу поднимать ‘VC-38NN’ всякий раз, когда строка строки содержит ‘Profoma invoice’. Приведенный ниже мой код по-прежнему выводит все, как только строка поиска найдена.

 Payment date
receipt serial
Profoma invoice VC-38NN
Welcome again
  
 if(multilineString.toLowerCase().contains("Profoma invoice".toLowerCase()))
{
    System.out.println(multilineString "");
}
else 
{
    System.out.println("Profoma invoice not found");
}
  

Комментарии:

1. Я не вижу многострочную строку. Я вижу строку в одну строку.

2. Код выводит неизмененную MultiLineString плюс пустую строку. это выводит «все»

3. Изучите регулярные выражения (в частности, группы захвата).

4. @meriton Разбить с помощью n затем пройти с помощью for может быть лучше 🙂

5. «Мой приведенный ниже код по-прежнему печатает все, как только строка поиска найдена». — если вы имеете в виду, что ваш код выполняет «if-condition» вместо «else condition», то это именно то, что вы сказали ему делать. Вам нужно поработать над своим вопросом, чтобы объяснить нам, чего вы не понимаете в том, что делает код.

Ответ №1:

Вот два возможных решения:

 String input = "Payment daten"  
        "receipt serialn"  
        "Profoma invoice VC-38NNn"  
        "Welcome again";

// non-regex solution
String uppercased = input.toUpperCase();
// find "profoma invoice"
int profomaInvoiceIndex = uppercased.indexOf("PROFOMA INVOICE ");
if (profomaInvoiceIndex != -1) {
    // find the first new line character after "profoma invoice".
    int newLineIndex = uppercased.indexOf("n", profomaInvoiceIndex);
    if (newLineIndex == -1) { // if there is no new line after that, use the end of the string
        newLineIndex = uppercased.length();
    }
    int profomaInvoiceLength = "profoma invoice ".length();
    // substring from just after "profoma invoice" to the new line
    String result = uppercased.substring(profomaInvoiceIndex   profomaInvoiceLength, newLineIndex);
    System.out.println(result);
}

// regex solution
Matcher m = Pattern.compile("^profoma invoice (. )$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE).matcher(input);
if (m.find()) {
    System.out.println(m.group(1));
}
  

Ответ №2:

Объяснение в комментариях:

 public class StackOverflow55313851 {

    public final static String TEXT = "Profoma invoice";

    public static void main(String[] args) {
        String multilineString = "Payment daten"   
                   "receipt serialn"   
                   "Profoma invoice VC-38NNn"   
                   "Welcome again";

        // split text by line breaks
        String[] lines = multilineString.split("n");
        // iterate over every line
        for (String line : lines) {
            // if it contains desired text
            if (line.toLowerCase().contains(TEXT.toLowerCase())) {
                // find position of desired text in this line
                int indexOfInvoiceText = line.toLowerCase().indexOf(TEXT.toLowerCase());
                // get only part of the line following the desired text
                String invoiceNumber = line.substring(indexOfInvoiceText   TEXT.length()   1);
                System.out.println(invoiceNumber);
            }
        }
    }

}