0

I have one requirement where text field have information like below format:

String name = 'email,phone(Jason),mobile,address(Mason)';

Now what I want to do is create a Map<Key, List<String>> where key will be name in brackets ex: Jason/Mason and values will be whatever is before that name in parentheses. So output should be like:

OUTPUT: {Jason=(email,Phone), Mason=(mobile,address)}

I had tried different ways but unable to format string 'email,phone(Jason), mobile,address(Mason)'. As there are parentheses Is it even possible to achieve this?

1
  • 2
    Is the format of the text field set in stone here? The easiest solution here would probably be to use JSON for the input text. Otherwise, I imagine you're going to be using some combination of regex and methods from the String class. You should also edit your question to show us the attempt(s) you've made so far and include sample output from them (and/or the full, unmodified text and stack trace of any error(s) you're getting).
    – Derek F
    Commented Feb 27, 2023 at 15:32

1 Answer 1

1

That's an oddly weird request, but assuming you haven't overgeneralized, you could write something like this:

Map<String, List<String>> results = new Map<String, List<String>>();
String name = 'email,phone(Jason),mobile,address(Mason)';
while(name != '') {
    String key = name.substringBetween('(',')');
    String[] values = name.substringBefore('(').split(',');
    results.put(key, values);
    name = name.substringAfter(')').removeStart(',');
}

Which outputs:

{Jason=(email, phone), Mason=(mobile, address)}
1
  • Thank you so much for the reply. This one is so simple and clean. I was making it over complicated by tracking it using indexing. Commented Feb 27, 2023 at 16:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .