views:

62

answers:

3

(If you can make a better title, please do)

Hi,

I need to make sure a string matches the following regex:

^[0-9a-zA-Z]{1}[0-9a-zA-Z\.\-_]*$
(Starts with a letter or number, then any number of letters, numbers, dots, dashes or underscores)

But given that, I need to make sure it doesn't match a Guid, my Guid matching reg-ex looks like this (obviously, this needs to be negated in the merged result):

^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$

The last requirement here is that they must (if it's possible) be merged into a single expression.

+5  A: 

You can just use a negative lookahead assertion.

(?!YourGuidExpression)YourOtherExpression
Daniel Brückner
+3  A: 

The simplest way to do this, if your language supports it, is to use a negative lookahead:

^(?!([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$)[0-9a-zA-Z]{1}[0-9a-zA-Z\.\-_]*$
Mark Byers
A: 

I would suggest using both regular expressions rather than combining them. This will be easier to maintain as well as faster in most cases. Something like this:

if (m/^[0-9a-zA-Z]{1}[0-9a-zA-Z\.\-_]*$/) {
  my $m = $&;
  if ($m =~ m/^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$/) {
    return null;
  } else {
    return $m;
  } 
} else {
  return null;
}
Charles