Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple matches with Postgres regexp_matches

I trying to use Postgres regexp_matches function to pull hashtags out of a string... The following example returns only a match - how do I extract both hashtags?

regexp_matches("Hello #world #planet", '#([A-Za-z0-9]+)')

Cheers, Andrei

like image 675
Andrei Taraschuk Avatar asked Apr 10 '16 23:04

Andrei Taraschuk


People also ask

How do I match strings with regular expression in PostgreSQL?

The output contains the ‘#eduCBA’ and ‘#PostgreSQL’ string, which means matching strings with regular expression defined in pattern. In the above example, the regular expression is “ ( [A-Za-z0-9]+)”, which matches the string, which begins with a character hash (#) and is followed by any alphanumeric characters.

How do I use regexp_matches() function in PostgreSQL?

The PostgreSQL REGEXP_MATCHES () function matches a regular expression against a string and returns matched substrings. The following illustrates the syntax of the PostgreSQL REGEXP_MATCHES () function: The source is a string that you want to extract substrings that match a regular expression.

How many rows does PostgreSQL regex return?

The PostgreSQL Regex function returns no row, one row, or multiple rows per defined pattern. The PostgreSQL Regex function may return zero, one, or several rows depending on the pattern specified. The PostgreSQL Regex functions allow us to search for any word in the needed string at any position, or we can search for simply the first occurrence.

What are the different types of pattern matching in PostgreSQL?

There are three separate approaches to pattern matching provided by PostgreSQL: the traditional SQL LIKE operator, the more recent SIMILAR TO operator (added in SQL:1999), and POSIX-style regular expressions.


1 Answers

You should enclose string literal with ' not ". Adding 'g' as proposed in comment should help:

SELECT regexp_matches('Hello #world #planet', '#([A-Za-z0-9]+)', 'g')

SqlFiddleDemo

╔════════════════╗
║ regexp_matches ║
╠════════════════╣
║ world          ║
║ planet         ║
╚════════════════╝
like image 104
Lukasz Szozda Avatar answered Oct 19 '22 20:10

Lukasz Szozda