This is based on a question previously asked which was deleted by the OP but it got me thinking and playing round with it, and I managed to do it without using a regex (only (I)LIKE() % or _ allowed).
- The question is also a lesson in the perils of allowing users to enter free text!
However, my solution is quite cumbersome and I've wracked my brains to see if I could find a more elegant solution, but no joy.
I'm not going to put my own solution forward yet.
A typical string might be like this:
'First order 437.3/10-87 16NY100013XX55 - Return'
So, the only thing you can be sure of is that the string (order_name) starts with '437.' and that it ends with the last digit in the string.
- N.B. The text following the order is arbitrary: its only constraint is that it can't contain a digit!
So, the result for this particular example would be
'437.3/10-87 16NY100013XX55'
So, my table and data are below and also on the fiddle here:
CREATE TABLE t1
(
id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
order_name TEXT NOT NULL
);
strings:
INSERT INTO t1 (order_name) VALUES
('First order 437.8/03-87 22LA190028YV7ER55'),
('Second order 437.8-03-87 22LA19'),
('First order 437.3/10-87 16NY100013XX55 - Return'),
('Order 21.02.2022 437.8/10-87 16WA239766'),
('437.8/10-87 16NY10023456YY78 - Paid'),
('First order (437.8/03-87 22LA190028)'),
('Visit 02.02.2023 Order 437.5/10-87 16DC107765X56 REFUND'),
('Visit 02.02.2023 Order 437.5/10-87 16DC1077657FFR56REFUND'),
('Visit 02.02.2023 Order 437.5/10-87 16DC107765745 - Reorder');
Desired result:
Order Text
437.8/03-87 22LA190028YV7ER55
437.8-03-87 22LA19
437.3/10-87 16NY100013XX55
437.8/10-87 16WA239766
437.8/10-87 16NY10023456YY78
437.8/03-87 22LA190028
437.5/10-87 16DC107765X56
437.5/10-87 16DC1077657FFR56
437.5/10-87 16DC107765745
The fiddle is PostgreSQL 16, but I've checked and it works back to version 10. The question is PostgreSQL based, but I'm open to elegant solutions from other systems.


(I)LIKE() % or _allowed. The regex engine is overhead that isn't present in the simplePOSITION(),SUBSTRING(),REPLACE()(or othersTRANSLATE()&c...) - the general advice is (and my own ad-hoc testing bears this out) is that regexes should only be used when all other avenues have been exhausted. I just became intrigued by this question for some reason (sad life, nothing else to do... don't ask! :-) ) - I'll set up a benchmark and include a regex solution and we can see - based on tests and facts. Gross breach of SO tradition, but hey! Have a go?postgresandregextags. I only caught it when I narrowed it down to recent questions with aregexin just the body and a bounty that was added by not necessarily awarded. I'm still somewhat curious about the code you mentioned you were planning to share.