How to select a piece of Java string?

3

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?

    
asked by anonymous 29.03.2017 / 15:14

3 answers

3

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);
        System.out.println(resultado);
    }
}

Output:

  

646646

Explanation

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 .

    
29.03.2017 / 16:05
5

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]+)", "");
        System.out.println(z);
    }
}

See here working on ideone.

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

    
29.03.2017 / 15:20
1

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 = matcher.group(1);
        System.out.println(resultado);
    }
}

Ideone

    
29.03.2017 / 16:20