开发者

Combining .net Regular expressions

I am trying to merge two .net regular expressions into one. The following expressions are validating excel like cell names.

Regex.IsMatch(name, @"^[A-Za-z]{1}[\w\.]*$") && 
    !Regex.IsMatch(name, @"^[A-Za-z]{1,2}\d+$");

The first part ensur开发者_开发知识库es the cell name starts with a character and can be any length. The second ensures the cell name is not a cell reference; for example, A1, AA1, AA11, etc.


The following might work:

^[A-Za-z](?![A-Za-z]?\d+$)[\w.]*$

Since the first regex must match and the second must not, I moved parts of the second one into a negative lookahead which doesn't consume any characters in the match but still would enable the RE to reject strings that would have matched the second RE.


I believe you can eliminate the 2nd call to IsMatch and it shouldn't make a difference.

Regex.IsMatch(name, @"^[A-Za-z]{1}[\w.]*$")

This pattern in itsslef insures that no digits (0 - 9) are present in the string, so it should be sufficient.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜