在java中解析字符串以获取信息

时间:2015-08-17 17:56:43

标签: java string string-parsing

我想知道是否有办法解析此字符串以获取与每个描述符关联的数值。我想使用这些值来更新总数和平均值等。

字符串如下所示:

D/TESTING:﹕ 17-08-2015 13:28:41 -0400
    Bill Amount: 56.23      Tip Amount: 11.25
    Total Amount: 67.48     Bill Split: 1
    Tip Percent: 20.00

字符串的代码如下所示:

String currentTransReport = getTime() +
            "\nBill Amount: " + twoSpaces.format(getBillAmount()) +
            "\t\tTip Amount: " + twoSpaces.format(getTipAmount()) +
            "\nTotal Amount: " + twoSpaces.format(getBillTotal()) +
            "\t\tBill Split: " + getNumOfSplitss() +
            "\nTip Percent: " + twoSpaces.format(getTipPercentage() * 100);

我想提取每个值,比如账单金额,然后将值存储在要使用的变量中。我可以访问带有信息的唯一字符串,而不是构建字符串的代码或信息。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情开始吧?这将使所有字符从您当前查找的子字符串后面开始,并以子字符串后面的制表符结尾。您可能需要将此制表符更改为其他内容。希望语法没问题,我已经离开java一段时间了。

String myString = "17-08-2015 13:28:41 -0400Bill Amount: 56.23      Tip Amount: 11.25  Total Amount: 67.48     Bill Split: 1 Tip Percent: 20.00 ";
String substrings[] = {"Bill Amount: ", "Tip Amount: ", "Total Amount: ", "Bill Split: ", "Tip Percent: "};
String results[] = new String[5];

for (int i = 0; i < substrings.length; i++){
    int index = myString.indexOf(substrings[i]) + substrings[i].length(); // where to start looking
    String result = myString.substring(index, myString.indexOf(" ", index));
    results[i] = result;
}

刚刚确认,这主要是有效的,唯一的问题是字符串末尾没有“”字符。

答案 1 :(得分:0)

您可以使用正则表达式,如下所示:

Bill Amount: ([0-9.]+) *Tip Amount: ([0-9.]+).*Total Amount: ([0-9.]+) *Bill Split: ([0-9]+).*Tip Percent: ([0-9.]+)

代码段:

String pattern = "Bill Amount: ([0-9.]+)" +
               " *Tip Amount: ([0-9.]+)" +
               ".*Total Amount: ([0-9.]+)" +
               " *Bill Split: ([0-9]+)" +
               ".*Tip Percent: ([0-9.]+)"
Pattern p = Pattern.compile(pattern, Pattern.DOTALL);
Matcher m = p.matcher(textValue);
if (m.find()) {
    billAmount  = Double.parseDouble(m.group(1));
    tipAmount   = Double.parseDouble(m.group(2));
    totalAmount = Double.parseDouble(m.group(3));
    split       = Integer.parseInt(m.group(4));
    tipPct      = Double.parseDouble(m.group(5));
}

注意DOTALL,因此.*符合换行符。