简体   繁体   中英

How to identify combination of number and character in SQL

I have a requirement where I have to find number of records in a special pattern in the field ref_id in a table. It's a varchar column. I need to find all the records where 8th, 9th and 10th character are numeric+XX. That is it should be like 2XX or 8XX. I tried using regexp :digit: but no luck. Essentially I am looking for all records where 8th-10th characters are 1XX, 2XX, 3XX… etc

Using REGEXP_LIKE, replace table with Yours:

SELECT COUNT(*)
FROM table
WHERE REGEXP_LIKE(ref_id,'^.{7}[0-9]XX');

.{7} whatever seven characters

[0-9] 8th character digit

XX 9th and 10th characters X

Or with [:digit:] class as You are mentioning, You may use:

SELECT COUNT(*)
FROM table
WHERE REGEXP_LIKE(ref_id,'^.{7}[[:digit:]]XX');

This can also be achieved using standard non-regex SQL functions

select * from t where s like '________XX%'     -- any 8 characters and then XX
      AND translate( substr(s,8,1),'?0123456789','?') is  null; --8th one is numeric

DEMO

No need for a regexp:

select * from mytable where substr(ref_id, 8, 3) in ('0XX','1XX','2XX','3XX','4XX','5XX','6XX','7XX','8XX','9XX')

or

select * from mytable where substr(ref_id, 8, 3) in ('1XX','2XX','3XX','4XX','5XX','6XX','7XX','8XX','9XX')

I don't know if '0XX' is a valid match or not.

Regexp's tend to be slow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM