J Blaz
J Blaz

Reputation: 783

Matching strings with Regular Expressions c#

The program is given a String for the name of a cell in a spreadsheet. This spreadsheet can contain a cell with a name that starts with a letter a-zA-Z_ this has to be the case, anything else is invalid. After the first letter or underscore there can be any combination of letters numbers or underscores. For example:

______35we3I Is a valid name

123dfdf Is NOT a valid name.

If these strings exist I want to throw an exception. I am new to regular expressions but this is what I came up with and it doesn't work like I want it to.

@"[a-zA-Z_][a-zA-Z_|\d]*"

When The second example is passed in the Regex.IsMatch function returns true because the last half of the expression is valid. Is there a way to start from the beginning of the string always?

I should say that I tried using the {^} to acomplish the above condition but it doesnt accept anything when the carrot is there.

Upvotes: 1

Views: 130

Answers (2)

Doc Roms
Doc Roms

Reputation: 3308

For testing your regex, you've a very good website here

For your regex, you want to add a number validator in your regex:

@"^[0-9a-zA-Z_][a-zA-Z_\d]*"

with this, your two strings was validate.

@"^[a-zA-Z_][a-zA-Z_\d]*"

with this, just string started by not a number was validate.

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

You need to use the start and end anchors and you don't need to put | inside the character class. | inside the char class would match a literal | symbol.

@"^[a-zA-Z_][a-zA-Z_\d]*$"

Code:

String s = "123dfdf";
if (!Regex.IsMatch(s, @"^[a-zA-Z_][a-zA-Z_\d]*$")) {
Console.WriteLine("Error! Wrong format.");
}
else {
Console.WriteLine("Correct format.");
}

IDEONE

Upvotes: 4

Related Questions