简体   繁体   中英

Java Strip/Remove multiple words from a string

How to strip a string like this:

String a = "ItemStack{DIAMOND_HELMET x 1,UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=PRO, repair-cost=1}}"

I want to get something like

"Diamond_HELMET 1 UNSPECIFIC PRO"

The methods I have tried is just replacing a bunch of strings, but its a pain in the *** and looks awful. Just wondering if anyone have a better solution/option. Sorry forgot to add my own code :/

    String itemStackStringName = "ItemStack{DIAMOND_HELMET x 1, UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=PRO, repair-cost=1}}";
    String getItemStacks = itemStackStringName.replace("ItemStack","")
            .replace("{","").replace("}", "").replace("UNSPECIFIC_META:", "")
            .replace("display-name", "").replace("=","")
            .replace("meta-type", "").replace("repair-cost1", "")
            .replace("x", "").replace(",","");

    System.out.println(getItemStacks);
    "DIAMOND_HELMET  1 UNSPECIFIC PRO"

It works, but its just a huge mess.

If you know that's the type your strings are going to be, you can go ahead and do something like this:

String arr[] = a.split("\\{");//you get an array of 3 strings
String someFinalString = arr[1].split("x")[0].trim();//you get "DIAMOND_HELMET"
someFinalString += arr[1].split("x")[1].split(",")[0];
arr = arr[2].split("\\=");//you get an array of 4 strings
someFinalString += " " + arr[1].split(",")[0] + " " + arr[2].split(",")[0];

In the future please post what you tried to do. Splitting something like this will always look awful. You can always make it concise later.

Just a proof this works (and you can figure out by yourself how to get lowercase I guess): DrJava为简单起见

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM