[英]Get a specific part of a String in Java
I want to get specific parts of a String like: 我想获取String的特定部分,例如:
@org.junit.runners.Suite$SuiteClasses(value=[class data.XTest
, class data.YTest])
data.XTest
and data.YTest
are variable. data.XTest
和data.YTest
是变量。 Whats the best way to get the classes after the class
. 下课后
class
的最好办法是什么。
Required output: 要求的输出:
sTring[0] = data.XTest;
sTring[1] = data.YTest;
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.
适应您的要求。
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. 这是通过首先使用正则表达式提取
"...[class "
和"]"
之间的子字符串,然后对分隔的字符进行拆分以整齐地抽取目标字符串来实现的。
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]
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
Your data looks a lot like the toString
method of the Class
class. 您的数据看起来很像
Class
类的toString
方法。 You might want to use the API that the annotation and the Class
class make available. 您可能要使用批注和
Class
类可用的API。 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. 应该。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.