我需要以最有效的方式将其解析为字符串。我目前有这条线
D[date-string] T[time-string] N[name-string] M[message-string]
需要分别解析成四个字符串,
private String time; //would equal time-string
private String date; //would equal date-string
private String name; //would equal name-string
private String message; //would equal message-string
有没有简单的方法来做到这一点?
最佳答案
您可以使用正则表达式和组来匹配和提取此类数据: 例如,像这样的东西:
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 是整个匹配)。 然后,您必须将其更改为您想要接受的字符和模式。
关于Java 解析输出的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31406455/