Search code examples
postgresqlpostgresql-9.4regexp-like

PostgreSQL query to find a particular pattern in a text column


I have a text column in my database table which contains values like

A/B

A/B/C

A/B/C/D

A/B/C/D/E

Now, I want to select only those rows where this column value contains maximum three occurrences of '/'. For clarity - expected output should be:

A/B

A/B/C

A/B/C/D

Can anyone help me with such a query?


Solution

  • I think it would be easier to simply remove everything else and count the number of remaining characters:

    where length(regexp_replace(the_column, '[^/]', '', 'g')) <= 3
    

    Online example