Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use backreferences beyond 9 in a PostgreSQL regular expression?

The following regex simply extracts a part of the matched text using the backreferencing numbers:

SELECT regexp_replace('ABCDEFGHIJ','(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)','\2');
B

But how to backreference beyond the ninth matched substring?

The following won't work (returns the first match + 0), neither will the use of $10 or ${10}:

SELECT regexp_replace('ABCDEFGHIJ','(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)','\10')
A0

Note: this example was simplified for clarity, and would of course not necessitate going beyond backreference 9.

like image 383
Sébastien Clément Avatar asked Aug 11 '14 20:08

Sébastien Clément


1 Answers

As I said in my comment and in @p.s.w.g's answer, according to the documentation this isn't possible.

However, there are some other RegEx functions that may help. If you can update your question with a real world problem, I can help more specifically. But here is an example that solves your initial question using regexp_matches().

SELECT matches[10]
FROM regexp_matches('ABCDEFGHIJ', '(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)') AS matches;

 matches 
---------
 J
(1 row)
like image 124
Sam Avatar answered Oct 27 '22 15:10

Sam