Rearrange an irregular text file into a two-dimensional table

In the text file below, each row is separated into 4 columns by the space. The 1st column is type; the value is teacher or student, and they always exist. Columns 2-4 are name, age and city respectively; each column consists of two parts – column name and the value, which are separated by the comma; and certain column(s) could be missing.

````

student name=james age=13 city=toronto

teacher name=joe age=31 city=chicago

student age=21 city=paris

student city=mobile

````

Use Java to implement task: rearrange the text file into a regular two-dimensional table.

type

name

age

city

student

james

13

toronto

teacher

joe

31

chicago

student


21

paris

student



mobile

SPL code:


A

1

=create(type,name,age,city)

2

=file("data.txt").read@n()

3

=A2.(A1.record((t=~.split@1(""))(1)|t(2).property().align(["name","age","city"],name).(value)))

4

return A1

A1: Create an empty two-dimensional table;

A2: Read the text file as a sequence by rows.

A3: Parse each row of A2 as a record and write them to A1 in order. split@1 function splits a string into two parts according to the delimiter. property()function parses the name=value format string. align() function aligns a sequence according to the order of another sequence.

Read How to Call a SPL Script in Java to find how to integrate SPL into a Java application.

Source: https://stackoverflow.com/questions/75925781/extract-specific-string-from-java-without-using-grep-or-split