How to select a piece of the Java string?

Asked

Viewed 4,536 times

3

I have the String x = "@646646&".

I’d like to take everything in between @ and & and play in another String. Regardless of what is between these characters being number or not.

How do I do?

  • Use regular expressions to select only numbers, http://regexr.com/ here you can test your regular expression, for example to pick just type number \d and this will select only the numbers of your String

  • You want to take only numbers or whatever is between @ and &?

  • 1

    @Igorventurelli all this between @ and &

3 answers

5

Note: The question was edited and with that this answer ended up being invalidated. However, I will keep the answer here because it can still be useful.

Utilize x.replaceAll("(?:[^0-9]+)", ""), where x is your String.

See here an example:

public class Main {
    public static void main (String[] args) {
        String x = "@646646&";
        String z = x.replaceAll("(?:[^0-9]+)", "");
        System.out.println(z);
    }
}

See here working on ideone.

Instead of "(?:[^0-9]+)", you could also use the "(?:[^\\d]+)" which is equivalent.

  • Where you put the regular expression, it could be changed to \d so select only the numbers of the string?

  • @R.Santos Yes, I could. I put a last paragraph about this observation.

  • @Victorstafusa he edited the question. He wants to take whatever is between @ and &, whether or not it is a number.

  • @Igorventurelli Thanks for the warning.

3


You can use the methods indexOf() and substring() both of the class String:

public class Teste {
    public static void main(String[] args) {
        String x = "@646646&";
        int indexArroba = x.indexOf("@");
        int indexEComercial = x.indexOf("&");
        String resultado = x.substring(indexArroba + 1, indexEComercial);
        System.out.println(resultado);
    }
}

Exit:

646646


Explanation

The method indexOf() returns the position of first occurrence found of String passed as parameter. If no occurrence is found return -1.

The method substring() returns a piece of a String.

Its parameters are:

  • int beginIndex : index from where you want this "piece" of String

  • int endIndex : index of how far you want that "piece" of String


Here you find the official class documentation String.

1

Still using regular expression you could catch the grouping

public static void main(String args[]) {
    String x = "@646646&";

    Pattern regex = Pattern.compile("@(.+)&");
    //Ou se sempre fosse apenas numeros
    //Pattern regex = Pattern.compile("@(\\d+)&");
    Matcher matcher = regex.matcher(x);

    while (matcher.find()) {
        String resultado = matcher.group(1);
        System.out.println(resultado);
    }
}

Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.