简体   繁体   中英

ORacle SQL Regular Expressions

I'm looking to create some regular expressions code for some testing. In the below I have created a Constraint Check for an email address.

     create table testemail (username varchar2(50) NOT NULL,
     Password varchar(15) Not NULL,
     CONSTRAINT pk_usertest PRIMARY KEY (username),
     CONSTRAINT un_emailtest CHECK (REGEXP_LIKE(username,'^([[:alnum:]]+)@[[:alnum:]]+.(com|net|org|edu|gov|mil)$'))

Is there a better way to have a constraint check when a new user creating an account?

Also, I'm trying to search a user by the name of 'Luke Haire' but my below sql queries returns no results:

 select * from customers where regexp_like (name, '^([L(u|i|o)ke]+)[\][Haire]$');

I don't really understand your first question. A check constraint is the best way to have a check constraints. That is why databases support it. There are worse ways, such as triggers, but typically the best way is using this built-in, standard capability.

Your specific constraint seems too constrained. Email addresses commonly contain "." and "-" as well.

As for the second question, the problem is the suffix. So try:

select *
from customers
where regexp_like(name, '^([L(u|i|o)ke]+)[\][Haire]@.*$');
---------------------------------------------------^

I should add that I prefer the above to the equivalent:

where regexp_like(name, '^([L(u|i|o)ke]+)[\][Haire]@');

The issue is the difference between like and regexp . like always matches the entire string. So, under most circumstances, I prefer to have regular expressions emulate this by explicitly having the beginning and end. This is to avoid confusion. I use like for simpler searches and regular expressions for more complex ones.

However, I would still expect this to get no matches because \\ is not an allowed character before the @ , according to the check constraint.

Your query doesn't return any rows because you have two mistakes in your pattern.

Second expected character, according to your pattern is \\ so in character list [\\] you should add space [\\ ] or [\\[:space:]] . You are missing quantifier for [Haire] character list. At the moment your pattern works like:

regexp_like ('Luke Haire', '^([L(u|i|o)ke]+)[\](H|a|i|r|e)$')

One possible pattern for your entry string is:

 regexp_like (name, '^([L(u|i|o)ke]+)[\ ][Haire].*$')

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