john
john

Reputation: 1747

Unexpected Regex.Match outcome in C#

Match match = Regex.Match(returnValue, @regex, RegexOptions.IgnoreCase);

The variables in the above line of code contain the following values:

returnValue : "Tags"

@regex : "[A-Z][a-z][a-z]"

I'm assuming the regex function match should fail as the word "Tags" has 3 lower case letters and not 2 as the regex variable shows. But, match.Success always returns true for the above code.

This has really got me confused, and any explanation would be appreciated. Thanks!

Update:

Here is a more detailed explanation on what I need. I'm trying to create something like a regex generator.

The user enters A for upper, a for lower and d for digits. Now if the user passes a word like Tags, I check the passed string to see if it fits into the user specified rule.

Here's my current logic:

  if (patternChars[strIndex] == 'A') 
{
     regexBuilder.Append("[A-Z]");
} else if (patternChars[strIndex] == 'a') 
{
     regexBuilder.Append("[a-z]");
} else if (patternChars[strIndex] == 'd') 
{
     regexBuilder.Append("\\d");
} else {
     regexBuilder.Append(patternChars[strIndex]);
}

I'm guessing this needs to be changed?

Upvotes: 1

Views: 88

Answers (3)

一无所有
一无所有

Reputation: 103

The Match(String, String, RegexOptions) method returns the first substring that matches a regular expression pattern in an input string;

 regexBuilder.Append("^");
  if (patternChars[strIndex] == 'A') 
{
 regexBuilder.Append("[A-Z]");
} else if (patternChars[strIndex] == 'a') 
{
 regexBuilder.Append("[a-z]");
} else if (patternChars[strIndex] == 'd') 
{
  regexBuilder.Append("\\d");
} else {
 regexBuilder.Append(patternChars[strIndex]);
}
regexBuilder.Append("$");

Upvotes: 1

Christian Sauer
Christian Sauer

Reputation: 10889

Try this:

@regex : "^[A-Z][a-z][a-z]$"

Explanation:

  • $ matches the line end,so your third group will match the lower case g, but then there are additional characters, causing $ not to match.

  • ^ matches the line start, preventing matches in the middle of the string, e,g guten Tag or aaaAaa

This should match only Tag, but not Tags. But it would also match Zag, Aaa, etc. pp. - do you really want that?

Third edit: you are using this line:

Match match = Regex.Match(returnValue, @regex, RegexOptions.IgnoreCase);

Why are you ignoring the case when you are doing case sensitive matches?

for your edit: It depends - WHEN your user wants to find that in a string, it is ok. If you want to find out if a given string as whole matches, you need to prepend "^" and append "$" at the end.

Upvotes: 3

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

You may try like this:

^[A-Z][a-z][a-z]$

Regex demo

Upvotes: 2

Related Questions