How to select a piece of Java string?

Posted on

Question :

I have String x = "@646646&" .

I would like to get everything between @ and & and play on other String . Regardless of what is between these characters be number or not.

How do I do it?


Answer :

You can use the methods indexOf() and substring() both of 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);





The indexOf() method returns the position of the first occurrence found of the String passed as parameter. If it does not find any occurrences it returns -1 .

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

Your parameters are:

  • int beginIndex : index where you want this “piece” of String to begin

  • int endIndex : index of how far you want this “piece” of String

Here you find the official documentation for class String .


Note: The question was edited and this response was eventually invalidated. However, I will keep the answer here because it can still be useful.

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

Here’s an example:

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

See here working on ideone.

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


Still using regular expression you could get 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 =;



Leave a Reply

Your email address will not be published. Required fields are marked *