Skip to content
Advertisement

Splitting String by column with regex

JavaScript

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:

JavaScript

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:

JavaScript

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

Advertisement

Answer

First trim leading column, then split on white space:

JavaScript

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