简体   繁体   中英

Split a complex String in Java.

I've go a complex String introduced by the user with this format:

Name: John

Surname: Doe Patrick

Age: Thirty-one `

I want to split and parse into an object Person with this 3 attributes, but I don't wanna include the fields (Name: , Surname: , Age: ) in the attributes of this class.

Could you help me to find a regexp or another way to do this? Thank you so much!

Try this regex, it will take in every line what is after ":" (two dots).

(?<=:\s)([^\n]+)

Regex live here.

You should have clear idea what the string format could be. For instance if the only place where : can occur is between the field name and its value, you have a good pattern, which you can follow. Splitting by new line, then by : will result into something like key value pairs, so you can map the [0] element of each pair as a field name, so you will know where to put the value (name, age, etc...).

The following algorithm is not very efficient, you may simplify it with regex for general splitting for example, but it shows the simplicity of the task

        String s = "Name: John\n" +
                "\n" +
                "Surname: Doe Patrick\n" +
                "\n" +
                "Age: Thirty-one";

        String[] lines = s.split("\n");
        for (String line : lines) {
            if (line.trim().equals("")) {
                continue;
            }

            String[] pair = line.split(":");
            if (pair[0].trim().equals("Name")) {
                System.out.println("Name is " + pair[1].trim()); // assign to the corresponding property
            } else if (pair[0].trim().equals("Surname")) {
                System.out.println("Surname is " + pair[1].trim());
            } else if (pair[0].trim().equals("Age")) {
                System.out.println("Age is " + pair[1].trim());
            }
        }

The output is:

Name is John
Surname is Doe Patrick
Age is Thirty-one

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