Match specific words in comma delimited string

I have a list of value that are allowed such as: the cat, the mouse, the dog, and the parrot. Now I want to have the possibility to add many values from this list in a cell separated with semicolon (;).

That means I can add:

The cat; The dog; The mouse

The cat; the parrot

The mouse; The cat

The parrot

But I can not add

The lion; the cat

The mouse; the parrot; Лев

The cat;(That means I can not add a semicolon at the end)

The cat; The mouse;

;(That means i can not just add a semi colon) I try to write a constraint using this function regexp_like but this does not work fine.

not REGEXP_LIKE (animal, '[^(the cat| the mouse |the dog|the parrot|; )]', 'i')

NB: animal is the column which I applied the constraint

2 ответа

Добавьте к строке разделитель, а затем сопоставьте его так:

REGEXP_LIKE(
  ';' || animal,
  '^(;\s*(the cat|the mouse|the dog|the parrot)\s*)*$',
  'i'
)

Обновление:

Вы можете использовать вторую таблицу (со ссылкой на внешний ключ) или вложенную таблицу:

CREATE TYPE stringlist IS TABLE OF VARCHAR2(4000);
/

CREATE TABLE animals (
  id          number,
  animal_list stringlist
) NESTED TABLE animal_list STORE AS animals__animal;

ALTER TABLE ANIMALS__ANIMAL ADD CONSTRAINT animals__animal__chk
  CHECK ( TRIM( BOTH FROM LOWER( column_value ) )
            IN ( 'the cat', 'the mouse', 'the dog', 'the parrot' ) );

INSERT INTO animals VALUES ( 1, StringList( 'the cat', ' the dog ' ) );
-- Succeeds
INSERT INTO animals VALUES ( 2, StringList( 'the cat', 'the horse' ) );
-- Fails with ORA-02290: check constraint (TEST.ANIMALS__ANIMAL__CHK) violated

Тогда вы можете сделать:

SELECT id,
       ( SELECT LISTAGG( COLUMN_VALUE, ';' ) WITHIN GROUP ( ORDER BY ROWNUM )
         FROM   TABLE( a.animal_list ) ) AS animals
FROM   animals a;

Какие выводы:

ID ANIMALS
-- -----------------
 1 the cat; the dog 

Что касается части регулярных выражений, я считаю, что это простейшее регулярное выражение проверки, которое не требует манипулирования данными (обратите внимание, что после ';' есть пробел)

^(the cat|the mouse|the dog|the parrot|; )+$
Другие вопросы по тегам