select *
from bha b
where b.bks similar to 'd{2}[A-Z](d{2})d\1';
The purpose is to regex but bks is in the form
12A56856 |
12A12812 |
12A898389 |
Although I already have this data in my database, the query is still not successful.
I hope you can help
Input: |
---|
45A78963 |
78C79364 |
14A56356 |
56K78978 |
Output: |
---|
14A56356 |
56K78978 |
2
Answers
I don’t think this was a typo. I think you tried to avoid the error:
Which was caused by your attempt to use a backreference
1
in aSIMILAR TO
regex syntax. The message is a bit confusing because Postgres’ implementation ofSIMILAR TO
simply doesn’t support backreferences, at all – which I think it should say openly instead of sounding like you’re doing them wrong.Your addition of another backslash to get a
\1
got rid of the error, but that’s because this made the pattern look for a literal backslashfollowed by a literal
1
in that spot, matching things like'56K7891'
.@Stefanov‘s fix works because the
~
operator uses POSIX regular expression syntax, which does support backreferences.If you need to handle your third example
12A
89
83
89
with two identical pairs of digits separated by more than one digit, add a+
(or a*
if you also allow zero digits between those pairs):demo at db<>fiddle
If your data realy is structured as in the data provided then there is no need for regex – it could be done simply using SubStr() function. Just compare your string’s positions 4,5 against positions 7,8. You can add another test checking if the positions are numbers or not: