2012-03-19 74 views
1

我希望得到一個字符串的特定部分,如:得到一個字符串的特定部分在Java中

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

data.XTestdata.YTest是可變的。 什麼是class之後獲得課程的最佳方式。

需要的輸出:

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

你真的* *希望他們在一個數組? – Bohemian 2012-03-19 13:39:07

+0

或列表。問題是如何最好地得到這個字符串的部分,所以我可以使用反射 – ctekk 2012-03-19 13:41:04

回答

2

這個怎麼樣班輪:

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

這是通過先使用正則表達式來提取"...[class ""]"之間的字符串,然後分割上分離字符整齊地挖出目標字符串。

這是一個測試:

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)); 
} 

輸出:

[data.XTest, data.YTest] 
1
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 
+0

這個失敗,因爲它不會修剪sTring [1]'結尾的「])」。 – 2012-03-19 13:39:21

2

我會使用正則表達式。

// 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)); 
} 

產生

data.XTest 
data.YTest 

爲您的樣品輸入字符串。適應您的要求。

1

您的數據看起來很像Class類的toString方法。您可能想要使用註釋和類提供的API。我認爲是這樣的:

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(); 

應該給它。

+0

在註釋中找不到值() – ctekk 2012-03-19 13:47:27

+0

您需要用註釋的類型聲明'a'。我相應地更新了我的代碼。 – 2012-03-19 14:20:46

+0

好的我想我明白了,非常感謝! – ctekk 2012-03-19 14:34:01

相關問題