Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only letters which are followed by a number

I am trying to select some codes from a PostgreSQl table. I only want the codes that have numbers in them e.g

GD123 
GD564

I don't want to pick any codes like `GDTG GDCNB

Here's my query so far:

select regexp_matches(no_, '[a-zA-Z0-9]*$')
from myschema.mytable

which of course doesn't work. Any help appreciated.

like image 803
kanataki Avatar asked Sep 05 '25 02:09

kanataki


2 Answers

The pattern to match a string that has at least 1 letter followed by at least 1 number is '[A-Za-z]+[0-9]+'.

Now, if the valid patterns had to start with two letters, and then have 3 digits after as your examples show, then replace the + with {2} & {4} respectively, and enclose the pattern in ^$, like this: '^[A-Za-z]{2}[0-9]{3}$'

The regex match operator is ~ which you can use in the where clause:

SELECT no_
FROM myschema.mytable
WHERE no_ ~ '[A-Za-z]+[0-9]+'
like image 84
Haleemur Ali Avatar answered Sep 07 '25 22:09

Haleemur Ali


You may use

CREATE TABLE tb1
    (s character varying)
;

INSERT INTO tb1
    (s)
VALUES
    ('GD123'),
    ('12345'),
    ('GDFGH')
;

SELECT * FROM tb1 WHERE s ~ '^(?![A-Za-z]+$)[a-zA-Z0-9]+$';

Result:

enter image description here

Details

  • ^ - start of string
  • (?![A-Za-z]+$) - a negative lookahead that fails the match if there are only letters to the end of the string
  • [a-zA-Z0-9]+ - 1 or more alphanumeric chars
  • $ - end of string.

If you want to avoid matching 12345, use

'^(?![A-Za-z]+$)(?![0-9]+$)[a-zA-Z0-9]+$'

Here, (?![0-9]+$) will similarly fail the match if, from the string start, all chars up to the end of the string are digits. Result:

enter image description here

like image 22
Wiktor Stribiżew Avatar answered Sep 07 '25 21:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!