Arian
Arian

Reputation: 3241

Get a specific part of a String in Java

I want to get specific parts of a String like:

@org.junit.runners.Suite$SuiteClasses(value=[class data.XTest
, class data.YTest])

data.XTest and data.YTest are variable. Whats the best way to get the classes after the class.

Required output:

sTring[0] = data.XTest;
sTring[1] = data.YTest;

Upvotes: 1

Views: 2084

Answers (4)

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

Your data looks a lot like the toString method of the Class class. You might want to use the API that the annotation and the Class class make available. I think something like:

SuiteClasses a = ...; <- Put the annotation object here instead of calling toString on it
Class[] c = a.value();
sTring[0] = c[0].getName();
sTring[1] = c[1].getName();

should to it.

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117587

String s = "@org.junit.runners.Suite$SuiteClasses(value=[class data.XTest, class data.YTest])";
String temp = "value=[class ";
s = s.substring(s.indexOf(temp) + temp.length(), s.indexOf("])"));
String[] arr = s.split(", class ");
// sTring[0] = arr[0];
// sTring[1] = arr[1];
System.out.println(arr[0]);
System.out.println(arr[1]);

OUTPUT:

data.XTest
data.YTest

Upvotes: 1

Bohemian
Bohemian

Reputation: 425023

How about this one-liner:

String[] parts = input.replaceAll(".*\\[class (.*)\\].*", "$1").split(", class ");

This works by first using regex to extract the substring between "...[class " and "]", then splits on the separating chars to neatly pluck out the target strings.

Here's a test:

public static void main(String[] args) {
    String input = "@org.junit.runners.Suite$SuiteClasses(value=[class data.XTest, class data.YTest])";
    String[] parts = input.replaceAll(".*\\[class (.*)\\].*", "$1").split(", class ");
    System.out.println(Arrays.toString(parts));
}

Output:

[data.XTest, data.YTest]

Upvotes: 2

claesv
claesv

Reputation: 2113

I'd use regular expressions.

// uses capturing group for characters other than "," "]" and whitespace...
Pattern pattern = Pattern.compile("class ([^,\\]\\s]+)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

yields

data.XTest
data.YTest

for your sample input string. Adapt to your requirements.

Upvotes: 2

Related Questions