The following table contains a list of very useful regular expressions which can be used in C#/.NET or other RegEx-capable programming languages. Be aware that the expressions in the table are designed for .NET and may use .NET-specific sequences!
RegEx-Tester is an extremely useful litte tool which may help developing and validating complex regular expressions.
Regex | Description |
---|---|
@"<\s*(\w+)\s*((""|').*?(""|')|[^'"">]+)*?\s*>" | Matches any string that looks like a XML / HTML tag (while ignoring contents of strings). Groups[1] = Tagname |
@"^([\w0-9_\-\.]+)@([\w0-9_\-\.]+?)\.(\w{2,})" | Matches an email address. Groups[1] = Name Groups[2] = Domain Groups[3] = TLD |
@"^([a-z]:\\)?([^\\\n]+\\)*?([^\\\n]+)$" | Matches a file path Groups[1] = Drive (if absolute path) Groups[2] = Array of directories (if present) Groups[3] = Filename |
@"^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3,3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$" | Validates a IP Address (incl. IP range) Groups[2] = Class C Network Groups[3] = Class C Host |
@"^((0|128|192|224|240|248|252|254|255)\.){3,3}(0|128|192|224|240|248|252|254|255)" | Validates a Subnet-Mask (incl. valid range) |
@"^[A-z_][\w\-]{2,15}$" or (german): @"^[A-zöäüÖÄÜ][\wöäüÖÄÜß\-]{2,15}$" | Username (3-16 characters, starting with letter or underscore) |
@"^((([A-z]+)://)?(\w+:\w+@)?(([\w\.\-~]+\.)?[\w\.\-~]+)(:\d+)?)?(/([^\n#?!$&'\(\)\[\]/:;=@]+?/)*([^\n#?!$&'\(\)\[\]/:;=@]+)?(\?([\w%]+?=[\w%]+\&)*[\w%]+?=[\w%]+)?(#[\w%]+)?)?$" | Validates a URL (relative and absolute) in detail. Groups[3] = Protocol Groups[5] = username:password Groups[6] = Serveraddress Groups[9] = Port Groups[11] = Array of resource path Groups[12] = Resourcename Groups[13] = Parameter-String Groups[15] = Text Anchor |
Example of usage:
1 2 3 4 5 6 |
Regex regex = new Regex( REGEX , RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline); MatchCollection matchCollection = regex.Matches( TARGETSTRING ); foreach (Match match in matchCollection) { //do some work; } |