2015-08-17 63 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,所以.*匹配換行符。