1

I have following table in postgres 11.

col1
a;b;c
d/e/f
g and h
i with k
l + m

I would like to split this table based on certain delimiters (/,+,;,and,with]). The desired output is:

col1          col2
a;b;c         a
a;b;c         b
a;b;c         c
d/e/f         d
d/e/f         e
d/e/f         f
g and h       g
g and h       h
i with k      i
i with k      k
l + m         l
l + m         m

I am trying out below query.


select distinct * from table t,
UNNEST(REGEXP_SPLIT_TO_ARRAY(t.col1, '\s+[/|+|;|and|with]\s+')) s(col2)

7
  • 1
    Replace [/|+|;|and|with] with (?:[/+;]|and|with), a grouping construct. [...] is a bracket expression that only matches a single char defined inside it. Commented Jun 18, 2020 at 20:03
  • What is the purpose of adding '?:' Commented Jun 18, 2020 at 20:06
  • 1
    Non-capturing groups are a natural choice when the value matched by a grouping is not going to be retrieved/used later. Commented Jun 18, 2020 at 20:08
  • Actually split by ; is not working.. Commented Jun 18, 2020 at 20:11
  • 1
    Maybe that is due to spaces? Try \s*(?:[/+;]|and|with)\s*, or [/+;]|\s+(?:and|with)\s+ Commented Jun 18, 2020 at 20:13

1 Answer 1

1

You may use

[/+;]|\s+(?:and|with)\s+
\s*(?:[/+;]|and|with)\s*

See the regex demo #1 and regex demo #2.

Details

  • [/+;] - a +, / or ; char -| - or
  • \s+(?:and|with)\s+ - an and or with words enclosed with one or more whitespaces
  • \s*(?:[/+;]|and|with)\s* matches a /, +, ; or and or with strings enclosed with 0 or more whitespace chars.

Note (?:...) is a non-capturing group that is a natural choice when the value matched by a grouping construct is not going to be retrieved/used later.

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

Comments

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.