views:

249

answers:

2

In Oracle, is it possible to match both a particular string format and an empty string using a single regex?

Something along the lines of:

SELECT 1
  FROM DUAL
 WHERE REGEXP_LIKE('12345', '^([1-5]{5})|NULL$');

SELECT 1
  FROM DUAL
 WHERE REGEXP_LIKE('', '^([1-5]{5})|NULL$');

SELECT 1
  FROM DUAL
 WHERE REGEXP_LIKE(NULL, '^([1-5]{5})|NULL$');

where the 'NULL' portion of the regex is treated as a character class rather than a string literal and all three queries return 1.

I'm writing some data validation routines and would like to store/use just one regex to determine both the format and whether the input string can be empty -- rather than specifying those validation rules seperately for each data element.

Thanks, Jeff

+2  A: 

One option : Use

where rexp_like(expr, ''') or (expr is null)
blispr
+1, this solution doesn't rely on any magic values... once the syntax has been corrected... REGEXP_LIKE(expr, '^([1-5]{5})$)
Jeffrey Kemp
ironic... my syntax correction introduced a syntax error... :(
Jeffrey Kemp
Well, I was really looking for a single regular expression rather than an additional predicate. Codebender has a solution that meets that criterion.
jlpp
yes, Codebender's solution is good - but instead of an additional predicate it uses an additional function call. (not that that's a problem, mind you, just saying)
Jeffrey Kemp
"\s" also works to match an empty char, fyi. where regexp_like(nvl(expr,' '), 'abc|\s');
blispr
Thanks for your help babyLisper.
jlpp
+3  A: 

I don't think you can do so directly, but you could use nvl to make null values show up as a blank string or the string 'NULL'.

SELECT 1
  FROM DUAL
 WHERE REGEXP_LIKE(NVL(value, 'NULL'), '^([1-5]{5})|NULL$');
Tim Sylvester
That's a good solution. Thanks!
jlpp