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

Parsing a string for information in java

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

字符串如下所示:

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);

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

试试这样的方式开始?这将获取在您当前查找的子字符串之后开始并以子字符串之后的制表符结束的所有字符。您可能需要将此制表符更改为其他字符。希望语法没问题,我已经离开 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;
}

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

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

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,因此 .* 匹配换行符。