简体   繁体   中英

Oracle SQL, is it possible to get only varchar values that end with exactly 4 numbers?

I need to pull only values, from a varchar field, that end with exactly 4 numbers. For example, I need SMITH0821, but not SMITH1.

You can use REGEXP_LIKE, like this:

select * 
from YourTable t 
where REGEXP_LIKE(t.YourField, '.*[^:digit:][:digit:]{4}', 'n');

I'm not fully sure of the regex syntax, but you should be able to adjust it to your needs, using the docs on REGEXP_LIKE and the appendix of regular expressions .

@Andrew Logvinov has a valid point about matching too many digits. I think it's possible to negate that, by checking for a character class that is not a number. That would change the regex to this:

REGEXP_LIKE(t.YourField, '.*[^:digit:][:digit:]{4}', 'n');

Also, I'm not sure if you need a character in front of the numbers or that varchars with just 4 digits should match too. The following regex includes start ( ^ ) and end ( $ ) of string anchors (which may be needed in the expressions above as well). The rest of the expression first contains an optional group that can consist of any sequence of characters, as long as it ends with something else than a digit. After that optional group, 4 digits are needed right before the end of the value.

REGEXP_LIKE(t.YourField, '^(.*[^:digit:])?[:digit:]{4}$', 'n');

Unfortunately I cannot test them at the moment, and I don't use regex in Oracle very often, so I hope they work, or otherwise you can finetune them using the links I provided.

use regexp_like:

select * from tablename t
where regexp_like(t.columname, '[:alpha:][:digit:]{4}$')

This will ensure that you have an alpha character, followed by 4 digits, at the end of your username.

Here's a link to a decent doc: http://psoug.org/reference/regexp.html

You can use 4 underscores _ to match 4 characters after Smith as below:

  SELECT * from PERSON
   WHERE NAME LIKE 'SMITH____'

or use REGEXP_LIKE (documentation here ) to match 4 digits only as:

  SELECT * from PERSON
  WHERE REGEXP_LIKE (NAME , '^SMITH[0-9]{4}$', 'i');

'i' is used for case insensitive matching.

This will work:

select field2 from T1
where SUBSTR(field2, -4, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') AND
      SUBSTR(field2, -3, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') AND
      SUBSTR(field2, -2, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') AND
      SUBSTR(field2, -1, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');       

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