Skip to content
Advertisement

Splitting String by column with regex

4 
1 1
1 2 1
0
1 1

This is a String I get as input, but I just need every column, starting with the second column, aka:

  • 1 (second row)
  • 2 and 1 (third row)
  • 1 (fifth row)

This String has no fixed size in how many lines there could be or how many columns (columns being split by one space).

I think this is fairly easy by using:

string.split("enter regex here");

I need every column after the first. I’m still learning with regex but I just can’t seem to find a good solution. I know about "\r?\n" and " " for splitting but don’t know how to connect both to get every column. Any help is very appreciated 🙂

Another String could look like this:

2
1
1 2
9 3 5
1 3
0 9 2 4
0

In that case, I would need 2, 3, 5, 3, 9, 2, 4.

Advertisement

Answer

First trim leading column, then split on white space:

String[] split = str.replaceAll("(?m)^\d+\s*", "").split("\s");

See live demo.

The replace uses the multiline flag (?m), which makes ^ match the start of every line, and s matches spaces, so the first column is effectively deleted from every line, but s also matches newlines, so lines with only one column are deleted entirely. Although the new lines are retained in lines with more than 1 column.

Because s matches space and newline, the split splits between columns and between (first column removed) lines, yielding the desired result.

I believe this is the least code required for a solution.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement