开发者

Complex(?) regex: Is expression, but not another

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

Hi,

I need to make sure a string matches the foll开发者_如何转开发owing 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.


You can just use a negative lookahead assertion.

(?!YourGuidExpression)YourOtherExpression


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\.\-_]*$


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜