How to get a part of a String?

1

I need to get only the [nItem:2] of the Phrase:

Nota fiscal - 502: Status do retorno da transmissão: 778 - Informado NCM inexistente [nItem:2]

Would anyone have any ideas?

Remembering that it only matters the excerpt [nItem: XXX]

    
asked by anonymous 25.07.2018 / 15:06

3 answers

6

We already have some answers that fit the scenario, however, I would like to share my solution using regular expressions.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class q317584 {

    public static void main(String[] args) {

        String linha = "Nota fiscal - 502: Status do retorno da transmissão: 778 - Informado NCM inexistente [nItem:2]";
        Pattern pattern = Pattern.compile("\[nItem:(\d*)]");
        Matcher matcher = pattern.matcher(linha);
        if(matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

One of the advantages of this approach is assertiveness.

Regardless of what comes before, after, extra spaces, spaces less, the pattern will always pick up the next number after the tag [nItem:

I also believe that it leaves the code cleaner and more intelligible, without using .split , .substring , which depend on magic numbers to make the solution workable.

    
25.07.2018 / 15:49
2

Taking into account your need from the clarifications in the comments of the question, this should suffice:

String linha = "Nota fiscal - 502: Status do retorno da transmissão: 778 - Informado NCM inexistente [nItem:2]";
System.out.println(linha.substring(linha.lastIndexOf(":")+1, linha.length()-1)); //imprimirá 2
    
25.07.2018 / 15:25
-1

Break the string with .split(" ") using the space as separator, and then get the last item in the list: P

    
25.07.2018 / 15:11