2

I'm trying to split the following string into rows such that every word is in its own row with the exception of words of a single character (e.g. a, i):

"the quick brown fox jumps over a lazy dog"

This is what I've been messing with in SQL Fiddle, but I can't get the right result:

SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over a lazy dog',  
  E'(\\s+)(?=\\w{2,})') AS foo;

The result:

the
quick
brown
fox
jumps
over a
lazy
dog

It's almost correct, but for some reason the a is being combined with over. I want to disregard the a completely.

What's the little thing I'm missing?

6
  • SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over a lazy dog', E'(?<=\\w{2,}) (?=\\w{2,})') AS foo;? Commented Oct 25, 2017 at 16:33
  • 2
    select regexp_split_to_table('the quick brown fox jumps over a i lazy dog', '\s+(\w\s+)*'); Commented Oct 25, 2017 at 17:30
  • @Abelisto Thank you! Very nice. Commented Oct 25, 2017 at 17:36
  • I'm working with version 9.6 and that may just be the reason. I will delete my answer and urge @Abelisto to write his or hers. Commented Oct 25, 2017 at 17:38
  • I'm also working with 9.6, so I'm unsure what the issue is. I appreciate your help regardless! Commented Oct 25, 2017 at 17:40

1 Answer 1

4

The one solution already provided in the comment:

select regexp_split_to_table('the quick brown fox jumps over a i lazy dog.', '\s+(\w\s+)*');

However it does not takes in account punctuation marks. So instead of splitting the string by delimiter(s) you cant to extract words from it using regexp_matches() function:

postgres=# select (regexp_matches('the quick brown fox;jumps over, a lazy dog.', '(\w{2,})', 'g'))[1];
-- or
postgres=# select unnest(regexp_matches('the quick brown fox;jumps over, a lazy dog.', '(\w{2,})', 'g'));
┌────────────────┐
│ regexp_matches │
╞════════════════╡
│ the            │
│ quick          │
│ brown          │
│ fox            │
│ jumps          │
│ over           │
│ lazy           │
│ dog            │
└────────────────┘
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.