Archive

Posts Tagged ‘Regular Expressions’

Regular Expressions: Count the occurences of characters set/group in a string

Let’s say, you would like to count the number of characters group, for example: all upper case chars in string. How to do it? That’s easy by regular expressions.

Pattern for all upper case chars will be just: [A-Z] So here is a code:

string text = "Hmm, how to count ALL UpperCase chars?";
int result = Regex.Matches(text, "[A-Z]").Count;
// result = 6

We can use of course multiple rules at once. For example, to count all occurences of UpperCase chars, digits and 2 special symbols “#?”

string text = "#Hmm#, how to count ALL UpperCase chars?";
// pattern [A-Z] for UpperCase, [0-9] for numeric, [#?] for our special symbols
string pattern = @"[A-Z0-9#?]";
int result = Regex.Matches(text, pattern).Count;
// result = 9

and another trivial example.. Count all comma in a string.

string text = "1, 2, or maybe 3?";
string pattern = @"[,]";
int result = Regex.Matches(text, pattern).Count;
// result = 2

Regular Expressions: Remove all special characters from a string, allowing only alphanumeric and chars: ‘.’ and ‘-’

Remove all special characters from a string, allowing only alphanumeric and chars: ‘.’ and ‘-’

Example:

string source = ".ąśę0123^%($&Marek&*(@&@#-";
string result
  = System.Text.RegularExpressions.Regex.Replace(source, @"[^\w\.-]", "");
// result= ".ąśę0123Marek-"

Regular Expressions: Only numbers, letters, spaces and restricted string length

Only numbers, capital, small letters (English) and spaces are allowed. String length must be between 1 to 10 characters.

Regex:

^[A-Za-z0-9 ]{1,10}$

If you would like to add some chars for example: ,.- then just add them like that:

Regex:

^[A-Za-z0-9 ,.-]{1,10}$

Regular Expressions: Time hh:mm validation 24 hours format

Check if time is in 24h format hh:mm For example these values are valid: 01:00 (leading zero is mandatory), 05:01, 13:00, 23:59. For example these values are not valid: 24:00, 1:30, 05:60, 12|34 etc.

Regex:

([0-1]\d|2[0-3]):([0-5]\d)

Regular Expressions: Internet email address format validation

Valid format: whatever@whatever.whatever

Regex:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Regular Expressions: How to match all except one character

You can match the characters not within a range by complementing the set. This is indicated by including a “^” as the first character of the class; “^” elsewhere will simply match the “^” character. For example, [^,] will match any character except “,”.