2015-08-17 27 views
1

我想知道是否有办法解析此字符串以获取与每个描述符关联的数值。我想用这些值来更新总计和平均值等。解析字符串中的信息在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); 

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

+0

当然,你有什么尝试? – CubeJockey

+1

其中一种可能性是:使用“space”作为分隔符来分割字符串,然后检查是否可以将每个数组元素解析为浮点数。如果可以,解析它并将其添加到不同的浮点变量。 –

+0

你会想要split()方法(在制表符和换行符上),并且可能是一个简单的正则表达式。 – Michelle

回答

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

刚刚确认,这大部分工作,只有问题是没有字符“”字符的末尾。

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