Regular expression to break a comma-separated string into separate lines

I have a file with many lines. Each row has a column that can contain values ​​separated by commas. I need each line to be different (i.e. Comma separated values).

Here's an example line:

AB AB10, AB11, AB12, AB15, AB16, AB21, AB22, AB23, AB24, AB25, AB99 ABERDEEN Aberdeenshire

Columns are separated by commas (postal code area, postal codes, postal city, former postal environment).

Thus, the specified string will turn into:

AB AB10 ABERDEEN Aberdeenshire
AB AB11 ABERDEEN Aberdeenshire
AB AB12 ABERDEEN Aberdeenshire
...
...

I tried the following but it didn't work ...

(. +) \ t (([0-9A-Z] +),) + \ t (. +) \ t (. +)
+2


a source to share


3 answers


I agree that RegEx is not the best way to go, but it should work if that's all you have available. (Runs multiple times until there are no more matches)

Edit



Updated by the OP's final decision from comments.

Find: (.+)\t([^,\s]+),([^\t]+)\t(.+)
Replace: \1\t\2\t\4\r\1\t\3\t\4

      

0


a source


What you want to do is explode one line in many by creating permutations. You can probably do this with regular expressions if there is only one column with more than one value, but if there are multiple columns with more than one value, there will already be many possible permutations (e.g. mx n combinations where m and n is the number of values ​​in two columns with multiple values).



I don't think regular expressions will be the right tool for this task.

0


a source


I agree with stakx that this doesn't seem like a good place for regexes.

I would write a small program that reads each line, splits the line into columns, splits each corresponding column into a list of values, and then repeats all combinations of them, outputting each line.

Assuming only one column, which can have multiple tokens, basically looks like this:

while not InputFile.EndOfFile:
  line = InputFile.readline();
  columns = line.split('\t'); //Assuming 1-based array, so indexes 1-4
  col2values = columns[2].split(',');
  for each value in col2values:
    OutputFile.WriteLine(columns[1]+'\t'+value+'\t'+columns[3]+'\t'+columns[4]);

      

If multiple columns can have multiple values, just put another loop inside each one.

0


a source







All Articles