如何拆分字符串以删除某些部件

时间:2012-07-05 11:41:13

标签: java split

我有一个以这种格式保存字符串的文件:

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,")
} 

请帮我把垃圾放在中间和最后。

4 个答案:

答案 0 :(得分: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);

<强>输出:

  

ACHMU(ACH支付系统菜单 - 在线服务)

答案 1 :(得分:2)

您可以使用

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

答案 2 :(得分: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

答案 3 :(得分:1)

如果要替换的字符串始终为“[2:s,161”,则将其替换为空字符串或空格(如果可接受的话)。同样,对于其他字符串也是如此。

str.replace("[2:s,161,", '');