Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular expression maximum occurrences

Status
Not open for further replies.

DarwinIT

Programmer
Apr 25, 2008
142
0
0
US
Regex testExp = new Regex("[0-9a-zA-Z]{3,6}");
MessageBox.Show(testExp.IsMatch(txtIDS.Text).ToString());

From what I read - this regular expression should return True as long as I have an alpha numeric string of 3 to 6 characters. The minimum quantifier works but the maximum is not since it returns true with 7, 8, 9 etc. characters. Am I doing something wrong? Or perhaps C# doesn't support this ??
 
If you want max 6 no longer exists anywhere in the string to match, add a negative lookahead.
[tt] Regex testExp = new Regex("[0-9a-zA-Z]{3,6}[blue](?![0-9a-zA-Z])")[/blue];[/tt]
 
Further note:
... and then the lower limit needs enforcement too. Hence the complete pattern should read like this.
[tt] Regex testExp = new Regex("[blue](?<![0-9a-zA-Z])[/blue][0-9a-zA-Z]{3,6}[blue](?![0-9a-zA-Z])[/blue]");[/tt]
 
Why not just do the following?

Regex testExp = new Regex("^[0-9a-zA-Z]{3,6}$");

From the post, I'm assuming that non alpha-numeric characters are allowed.
 
Neswalt has the best answer. Needed the ^ to preface the expression and the $ at the end. I didn't want non-alphanumerics so added a @ in front of the whole expression and now it works. Thanks!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top