我需要以最有效的方式将其解析为字符串。我目前有这条线
PowerMockito.mockStatic(Color.class);
PowerMockito.when(Color.rgb(Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
int red = (int) invocation.getArguments()[0];
int green = (int) invocation.getArguments()[1];
int blue = (int) invocation.getArguments()[2];
return (0xFF << 24) | (red << 16) | (green << 8) | blue;
}
});
PowerMockito.when(Color.alpha(Mockito.anyInt())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return ((int)invocation.getArguments()[0])>>>24;
}
});
PowerMockito.when(Color.red(Mockito.anyInt())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return (((int)invocation.getArguments()[0])>>16) & 0xFF;
}
});
PowerMockito.when(Color.green(Mockito.anyInt())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return (((int)invocation.getArguments()[0])>>8) & 0XFF;
}
});
PowerMockito.when(Color.blue(Mockito.anyInt())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return (int)invocation.getArguments()[0] & 0xFF;
}
});
需要分别解析为四个字符串,
D[date-string] T[time-string] N[name-string] M[message-string]
有一种简单的方法吗?
答案 0 :(得分:1)
您可以使用正则表达式和组来匹配和提取这类数据: 例如,像:
Pattern p = Pattern.compile("D(\\w+) T(\\w+) N(\\w+) M(\\w+)");
Matcher m = p.matcher(yourString);
if (m.matches()){
String d = m.group(1);
String t = m.group(2);
String n = m.group(3);
String w = m.group(4);
}
括号内的模式被保存到组中,您可以在匹配后提取它(从1开始,因为0是整个匹配)。 然后,您必须将其更改为您要接受的字符和模式。
答案 1 :(得分:0)
我不确定我是否理解你,但看起来使用正则表达式是进行这种解析的最简单方法。
答案 2 :(得分:0)
以下逻辑可行。如何regix将不确定。但是下面的代码也可以,因为它不是循环的,所以我认为它可能是最佳的解决方案。
String s = "D[date-string] T[time-string] N[name-string] M[message-string]";
String[] str = s.split(" ");
String date = str[0].substring(str[0].indexOf("[")+1, str[0].lastIndexOf("]")); //would equal time-string
String time=str[1].substring(str[1].indexOf("[")+1, str[1].lastIndexOf("]")); //would equal date-string
String name=str[2].substring(str[2].indexOf("[")+1, str[2].lastIndexOf("]")); //would equal name-string
String message=str[3].substring(str[3].indexOf("[")+1, str[3].lastIndexOf("]"));
答案 3 :(得分:0)
答案 4 :(得分:0)
D [(。*?)]为日期!