2012-07-05 219 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 
相关问题