Skip to content

Instantly share code, notes, and snippets.

@thoemmi
Created May 20, 2013 17:40
Show Gist options
  • Save thoemmi/5613845 to your computer and use it in GitHub Desktop.
Save thoemmi/5613845 to your computer and use it in GitHub Desktop.
Regular expression for unsigned short
[TestFixture]
public class UshortRegexTest {
readonly Regex _ushortRegex = new Regex(@"^(
0 # 0
|
[1-9]\d{0,3} # 1-9999
|
[1-5]\d{4} # 10000-59999
|
6[0-4]\d\d\d # 60000-64999
|
65[0-4]\d\d # 65000-65499
|
655[0-2]\d # 65500-65529
|
6553[0-5] # 65530-65535
)$", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
[TestCase("0", true)]
[TestCase("-1", false)]
[TestCase("9", true)]
[TestCase("10", true)]
[TestCase("100", true)]
[TestCase("1000", true)]
[TestCase("10000", true)]
[TestCase("100000", false)]
[TestCase("60000", true)]
[TestCase("69999", false)]
[TestCase("65000", true)]
[TestCase("65999", false)]
[TestCase("65500", true)]
[TestCase("65599", false)]
[TestCase("65530", true)]
[TestCase("65539", false)]
[TestCase("65535", true)]
[TestCase("65536", false)]
public void Check(string s, bool expected) {
var isUshort = _ushortRegex.IsMatch(s);
Assert.AreEqual(expected, isUshort);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment