2

I have got a table with two columns: ID and cars. Sample data looks like:

ID  |  Cars
-----------------
1   |  opel, honda and land rover
2   |  ford and porshe, damaged
3   |  volkswagen
4   |  opel, seat, damaged

I would like to split it into:

ID  |  Cars
-----------------
1   |  opel
1   |  honda
1   |  land rover
2   |  ford
2   |  porshe, damaged
3   |  volkswagen
4   |  opel
4   |  seat, damaged

So the delimiter is and or , but not , damaged How to use regex to split it in postgresql?

EDIT:

And how to make it working for records like

5 | land rover and opel, and ford
6 | ford; mazda and toyota
1
  • What kind of car is "porshe"? Commented Feb 20, 2016 at 17:50

1 Answer 1

4

You can use regexp_split_to_table with a negative lookahead for damaged;

SELECT "ID", regexp_split_to_table("Cars", '((, (?!damaged))| and )') "Cars" 
FROM mytable;

 ID |      Cars
----+-----------------
  1 | opel
  1 | honda
  1 | land rover
  2 | ford
  2 | porshe, damaged
  3 | volkswagen
  4 | opel
  4 | seat, damaged
(8 rows)

An SQLfiddle to test with.

EDIT: For your new examples, the regex had to be tweaked a bit;

SELECT "ID", regexp_split_to_table("Cars", '(([,;] (?!damaged))|[,;]? and )') "Cars" 
FROM mytable;

Another SQLfiddle.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for quick reply! And how to add new rows? because this is just select query. Thanks!
@Mateusz Maybe you could add a new question for that with more info and examples what you want to do, the question does not even mention insertion of new rows or what the input or resulting format should be.
then I would duplicate my question, i think that is not okey on stackoverflow
@Mateusz Well, you have the select part that the question was about, I was thinking about the insertion you asked about in the comments that wasn't mentioned in the question :)
@Mateusz Since it'd be a substantial edit with new functionality, it's probably better to ask a new (self contained) question. You can always add a link to this question if needed as part of your explanation.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.