java – How to retrieve specific parts/values ​​from a string?


I have an ArrayList where I assemble a custom list that is displayed in a ListView . What I need is to pass the value of the selected item to another screen.

See below the method that will call the other screen:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Object obj = parent.getItemAtPosition(position);


    Intent it = new Intent(this, ActHolerite.class);

    startActivityForResult(it, 0);

In the above method I have the return below (in System.out ):

I/System.out﹕ {tipcal=Monthly Calculation, perref=April / 2015, codcal=405}

What I need to move to another screen is just the 405 (referring to codcal=405 ) because it is a key field of a select that I will use on this other screen.

How can I " unmount " this string and get only the number 405 ?


As you only need to get the number after codcal one way is using regular expressions.

For example, we can use this pattern: codcal=(\d+) . That is, it will "match" the string where there is codcal= followed by a number, in any quantity.

So, to retrieve it, we can search for this pattern in the string and, if it exists, retrieve the group we are interested in, the demarcated group number.

An example would be this:

final String string = "I/System.out: {tipcal=Cálculo Mensal, perref=Abril / 2015, codcal=405}";
final Pattern pat = Pattern.compile("codcal=(\\d+)");
final Matcher mat = pat.matcher(string);
if (mat.find()) {
Scroll to Top