简体   繁体   中英

How can I get a various strings inside different curly braces?

Imagine I have a String like this:

String str = "{} {2,3,4} {1} {6} {}";

And I want to obtain an array filled with the information inside the curly braces so the array would look like this:

array[0] = NULL, array[1] = "2,3,4", array[2] = "1", array[3] = "6", array[4] = NULL

I was thinking on maybe splitting the initial string str and then using some kind of regex to obtain what is inside the the curly braces. Is there any easier and more elegant way to do this? Thank you in advanced

Assuming they're all spaced the same way and always follow a rule with brackets:

public List<Integer> parseList(String list) {
    Stream.of(list.split(",")).map(Integer::parseInt).collect(Collectors.toList());
}

List<List<Integer>> automata = Stream.of(str.split("\\s")) //split into groups of braces
    .map(s -> s.substring(1, s.length() - 2)) //remove braces
    .map(Example::parseList) //map "1,2,3" into a List of [1,2,3]
    .collect(Collectors.toList());

Each List<Integer> in automata is a list of integers involved in a singular DFA/NFA. No regex necessary, and took about 2 minutes to write (To nod towards what @JamMaster is saying).

That said, in the true spirit of DFA you could write a character-by-character parser which works through the string in O(n) time. Might be worth extra credit if you did both.

using regex very less string operations. works faster, i believe


        Pattern pattern = Pattern.compile("\\{(.*?)\\}");
        Matcher matcher = pattern.matcher(str);

        while (matcher.find()) {
            System.out.println("->" + matcher.group().replaceAll("[{}]",""));
        }

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