在java中处理元组 [英] Processing tuples in java
本文介绍了在java中处理元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下格式处理一些数据:
I am processing some data with the following format:
String s = "{(30,2884090,1410450570357,235),(30,2863348,1410451100148,285)}"
有些疑惑困扰我:
此字符串中是否有两个条目(元组)?
是否有现成的数据结构我可以用来解析这个吗?
Is there any off-the-shelf data structure I can use to parse this?
有没有办法找出一个模式匹配,它可以返回一个列表给定字符串的两个字符串 ?
Is there any way to figure out a pattern matching which can return a list of two Strings for the given String?
推荐答案
就我而言知道,Java API没有可以开箱即用的东西。你需要为此编写一个小的解析器。
As far as I know, Java API does not have something that can be used out-of-box. You need to write a small parser for that.
为这样的事情编写解析器是微不足道的。这是一个好的开始:
Writing a parser for something like this is trivial. Here is a good start:
public class TupleParser {
/**
* Not in use at the moment.
*/
class TupleParserException extends RuntimeException {
public TupleParserException(String arg) {
super(arg);
}
}
/**
* Simple, recursive parser function.
*
* @param input A String which contains all the tuples.
* @param start Position where we start parsing.
* @param output Where to store the result tuple.
* @return An index of the character where we stopped parsing.
*/
public int parse(String input, int start, ArrayList output) {
int idx = start;
boolean finished = false;
String part = "";
while (idx < input.length() && !finished) {
char ch = input.charAt(idx);
switch (ch) {
case '{':
case '(':
case '[':
ArrayList newTuple = new ArrayList();
output.add(newTuple);
++idx;
idx = parse(input, idx, newTuple);
break;
case '}':
case ')':
case ']':
output.add(part);
finished = true;
break;
case ',':
output.add(part);
part = "";
break;
default:
part += ch;
} // switch
++idx;
} // while
return idx;
}
public ArrayList parse(String input) {
ArrayList ret = new ArrayList();
parse(input, 0, ret);
return ret;
}
public static void main(String[] args) {
String s = "{(30,2884090,1410450570357,235),(30,2863348,1410451100148,285)}";
TupleParser tp = new TupleParser();
ArrayList tuple = null;
try {
tuple = tp.parse(s);
System.out.println(tuple.toString());
tuple = tp.parse("1, 2, 5, 4"); // does not work yet
System.out.println(tuple.toString());
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
输出:
[[[30, 2884090, 1410450570357, 235], [30, 2863348, 1410451100148, 285]]]
[1, 2, 5]
这篇关于在java中处理元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文