tags:

views:

51

answers:

2

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 ensures 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.

+1  A: 

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.

Joey
Thanks Johannes, this solution got me most of the way. However, AA11Test is a valid "named cell" and this RE fails. This seems to catch all instances: ^[A-Za-z](?![A-Za-z]{0,2}\d+$)[\w.]*$
Greg
Eek, yes, forgot an anchor. Sorry.
Joey
+1  A: 

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.

Noldorin
The second RE must not match, though, so it's not a simple matter of folding both REs into one.
Joey
@Johannes: If the first matches, the second *cannot* match.
Noldorin
`\w` includes `0-9`. In fact, `"AA1"` is already a simple counter-example, given by the OP.
Joey