techie2k
techie2k

Reputation: 559

Regex pattern to convert comma separated String

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.

Upvotes: 0

Views: 1188

Answers (1)

Stanislav
Stanislav

Reputation: 28106

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.

Upvotes: 2

Related Questions