What you want has nothing to do with REGEX, as it is necessary to perform arithmetic operations.
Resolution
CREATE TABLE prefixos(
prefixo INTEGER
);
INSERT INTO prefixos (prefixo) VALUES
('429'),
('4299'),
('42999'),
('429998');
SELECT
P.prefixo,
min(P.prefixo - Q.pos)
FROM
prefixos P
LEFT JOIN (
SELECT prefixo,
substring('4299234180' from 0 for char_length(prefixo::varchar)+1)::integer as pos
FROM prefixos
) as Q ON Q.prefixo = P.prefixo
WHERE
(P.prefixo - Q.pos) > 0
GROUP BY
P.prefixo
ORDER BY
2
LIMIT 1
Explanation
To solve your problem I used the following logic :
- Capture the part of the number corresponding to the prefix size. Prefix
429
has Len = 3, so I’ll capture the first 3 characters of your number.
The part about doing that is :
LEFT JOIN (
SELECT prefixo,
substring('4299234180' from 0 for char_length(prefixo::varchar)+1)::integer as pos
FROM prefixos
) as Q ON Q.prefixo = P.prefixo
- After having the corresponding number to the prefix I perform an arithmetic operation to remove the ones equal to zero because I want to say that a higher prefix should suit.
(P.prefixo - Q.pos) > 0
- Finally, I check the least variation possible so having the prefix that best adapts.
min(P.prefixo - Q.pos)
Note
- The base I used was Postgresql, maybe you need to adapt something, because not all DBMS have the same functions.
thanks for the help but I only use mongodb as database, I have no experience with SQL only with NOSQL, and Regex is something native within mongodb.
– Rubens Fernandes