2012-07-05 97 views
0

我有一個包含字符串在此格式的文件:如何將一個字符串分解去除某些部分

ACHMU)][2:s,161,(ACH Payment Sys Menus - Online Services)][3:c,1,(M)][4:c,1,(N)] 
ACLSICZ)][2:s,161,(Report for Auto Closure)][3:c,1,(U)][4:c,1,(N)] 
ACMPS)][2:s,161,(Account Maintenance-Pre-shipment Account)][3:c,1,(U)][4:c,1,(N)] 
ACNPAINT)][2:s,161,(Interest Run For NPA Accounts)][3:c,1,(U)][4:c,1,(N)] 

我需要拆分字符串,使我在這個格式的數據:

ACHMU (ACH Payment Sys Menus - Online Services) 
ACLSICZ (Report for Auto Closure)...... 

基本上,我想刪除「)[2:s,161,」部分和「] [3:c,1,(M)] [4:c,1,(N)]」結束。將字符串分割幫助我嗎?下面的方法已經失敗:

FileInputStream fs = new FileInputStream(C:/Test.txt); 
BufferedReader br = new BufferedReader(new InputStreamReader(fs)); 
String str; 
while((str = br.readLine()) != null){ 
    String[] split = str.Split(")[2:s,161,") 
} 

請幫我弄到垃圾在中間和結束。

+1

是那裏,你得到任何錯誤或異常後的String [] =分裂str.Split( 「)[2:S,161」)? – FSP 2012-07-05 11:44:42

+0

沒有錯誤,只是字符串不能分割。 – ErrorNotFoundException 2012-07-05 11:45:53

+0

使用正則表達式作爲nhahtdh提到。 – 2012-07-05 11:52:22

回答

2

您可以使用

str.replaceFirst("(.*?)\\)\\].*?(\\(.*?\\))\\].*", "$1 $2"); 
+0

此代碼給出了正確答案,但在單行中。有沒有辦法讓每個輸出保持在自己的路線上?輸出看起來像ACHMU(ACH支付系統菜單 - 在線服務)ACLSICZ(自動關閉報告) – ErrorNotFoundException 2012-07-05 13:10:21

+0

'str.replaceFirst(「(。*?)\\)\\]。*?(\\(。*?\ \))\\]。*「,」$ 1 $ 2 \ n)'這是正確的答案我想要.........謝謝先生 – ErrorNotFoundException 2012-07-05 13:16:07

+0

@Stanley:輸出取決於您如何打印出來。 – nhahtdh 2012-07-05 14:00:46

3

的直接的方式,使用substring()indexOf()

String oldString = "ACHMU)][2:s,161,(ACH Payment Sys Menus - Online Services)][3:c,1,(M)][4:c,1,(N)]"; 
String firstPart = oldString.substring(0, oldString.indexOf(")")); // ACHMU 
String secondPart = oldString.substring(oldString.indexOf("(")); // (ACH Payment Sys Menus - Online Services)][3:c,1,(M)] 
String newString = firstPart + " " + secondPart.substring(0, secondPart.indexOf(")") + 1); // ACHMU (ACH Payment Sys Menus - Online Services) 
System.out.print(newString); 

OUTPUT:

ACHMU(ACH支付Sys系統菜單 - 在線服務)

+0

這個代碼給出了這個輸出: – ErrorNotFoundException 2012-07-05 13:03:55

+0

ACHMU(ACH支付系統菜單 - 在線服務)] [2:s,161,(Report for Auto (賬戶維護 - 裝運前賬戶)[2:s,161,關閉]] [3:c,1,(U)] [4:c,1,(N)] ACLSICZ ] [3:c,1,(U)] [4:c,1,(N)] ACMPS(賬戶維護 - 裝運前賬戶)] [2:s,161,(NPA賬戶的利息運行)] [3:C,1,(U)] [4:C,1,(N)] – ErrorNotFoundException 2012-07-05 13:06:12

1

如果要替換的字符串始終爲「[2:s,161,」,如果可以接受,請將其替換爲空字符串或空格。同樣,對於其他字符串也是如此。

str.replace("[2:s,161,", ''); 
2
FileInputStream fs = new FileInputStream(C:/Test.txt); 
BufferedReader br = new BufferedReader(new InputStreamReader(fs)); 
String str; 
String newStr; 
String completeNewStr=""; 
while((str = br.readLine()) != null) 
{ 
    newStr = str.replace(")][2:s,161,"," "); 
    newStr = str.replace("][3:c,1,(M)][4:c,1,(N)]",""); 
    completeNewStr+=newStr; 
} 

// completeNewStr is your final string 
相關問題