how to split a string in java with multiple delemeters?

Viewed 50

I have a string in java which looks like this "itemId":"{20044683-1111-D322-9A0B-9920EF6E9991}" which is actually a json request being sent to Java as a String ,now my requirement is to retrieve this part {20044683-1111-D322-9A0B-9920EF6E9991} i.e., the string between the braces and including the braces. how can this be done ?

2 Answers

I believe this is a duplicate of the following: How do I split a string in Java?

If you have a string, say

    String mystring = "{20044683-1111-D322-9A0B-9920EF6E9991}";

Then you can split it by doing something like the following:

    String[] individual_strings = string.split("{");

Then using this as an example, individual_strings[0] will be equal to the value inside of the brackets, excluding the first bracket.

    20044683-1111-D322-9A0B-9920EF6E9991}

Then you could perform another split on this to obtain the string in between the brackets.

    System.out.println(individual_strings[1].split("}"));

would give 20044683-1111-D322-9A0B-9920EF6E9991

Your question is a bit unclear - we don't know the data type of your object nor what you wish to do with it.

Now - if instead of doing a string split, you wanted to access a key value pair instead, then this completely depends on what is the type of your data object.

You mention that your string is "itemId":"{20044683-1111-D322-9A0B-9920EF6E9991}" but this is not a string data type, it looks more like a dictionary or JSON.

If you're looking for tips on how to access the key from an object, then we need more details including knowing the data type of your object.

Can you clarify what data type this is? (I would've asked this in comments, but I'm new to the site and can't comment yet)

For other references on how to access a key value pair in java, I recommend the following:

https://stackabuse.com/java-how-to-get-keys-and-values-from-a-map/

Hashmaps can be pretty great for this purpose.

public class Main
{
    public static void main(String[] args) {
        String str = "itemId:{20044683-1111-D322-9A0B-9920EF6E9991}"; 
        String[] words=str.split(":");
        System.out.println(words[1].substring(1,words[1].length() - 1));
    }
}
Related