0

Changing string with comma separated values to numbered new-line values

For example:

Input: a,b,c

Output:

1.a
2.b
3.c

Finding it hard to change it using regex pattern, instead of converting string to string array and looping through.

1
  • System.out.println(Arrays.toString("a,b,c".split("\\,"))); you can try this. Commented Oct 7, 2015 at 7:52

1 Answer 1

2

I'm not really sure, that it's possible to achive with only regex without any kind of a loop. As fore me, the solution with spliting the string into an array and iterating over it, is the most straightforward:

String value = "a,b,c";
String[] values = value.split(",");
String result = "";
for (int i=1; i<=values.length; i++) {
    result += i + "." + values[i-1] + "\n";
}

Sure, it's possible to do without splitting and any kind of arrays, but it could be a little bit awkward solution, like:

String value = "a,b,c";
Pattern pattern = Pattern.compile("[(^\\w+)]");
Matcher matcher = pattern.matcher(value.replaceAll("\\,", "\n"));
StringBuffer s = new StringBuffer();
int i = 0;
while (matcher.find()) {
    matcher.appendReplacement(s, ++i + "." + matcher.group());
}
System.out.println(s.toString());

Here the , sign is replaced with \n new line symbol and then we are looking for a groups of characters at the start of every line [(^\\w+)]. If any group is found, then we are appending to the start of this group a line number. But even here we have to use a loop to set the line number. And this logic is not as clear, as the first one.

Sign up to request clarification or add additional context in comments.

1 Comment

Looping I'm fond.. but pattern matching is the way I want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.