Using regular expressions to check for a minimum number of characters? - c#

I have the following code to validate usernames for an application:
Regex usernameRegex = new Regex("[A-Za-z0-9_]");
if (usernameRegex.IsMatch(MyTextBox.Text)) {
// Create account, etc.
}
How would I modify my regular expression to check if the username has a certain number of characters?

This expression validates only all text which contains any combination of A to Z, a to z and number 0 to 9. You can define the length of the string using the regex:
Regex reg= new Regex(#"^[A-Z]{3,}[a-z]{2,}\d*$")
{3,} and {2,} mean here that the string must have at least 3 capital characters, at least 2 small characters, and any amount of digit characters.
For example :
Valid : AAAbb, AAAbb2, AAAAAAbbbbb, AAAAAbbbbbb4343434
Invalid: AAb, Abb, AbAbabA, 1AAAbb,

To set a minimum (or maximum) range in a regular expression you can use the {from,to} syntax.
The following will only match a string with a minimum of 5 alpha numeric and underscore characters:
[A-Za-z0-9_]{5,}
And the following will match a minimum of 5 and maximum of 10:
[A-Za-z0-9_]{5,10}

[A-Za-z0-9_]
[] "brackets": are a group of characters you want to match.
A-Z: means it will match any alphabet capitalized within this range A-Z.
a-z: means it will match any small alphabet within this range a-z.
0-9: means it will match any digit in this range 0-9.
_: means it will match the "_" character.
now this regex will usually match the following: any character from a to z (small, capital), any number (from 0-9) and the underscore "_".
i.e. "a.,.B.,10.._" this will match "a, B, 10, _". but of course you need to add the singleline regex option.

Related

Regular expression to validate a mathematical formula

I need to validate a string using regex to confirm whether it is following a valid format.
The string can contain numbers, operators, space, dot, left parenthesis, right parenthesis, comma, these aggregate functions SUM, MAX, MIN, AVG and variables starting with letter V.
I found this regex ^[0-9+-/()., ]+$ this checks 0-9 (numbers); '+'; '-'; ''; '/'; '('; ')'; '.'; ','; ' '(space). But I am not able to include aggregate functions and letter V in this.
Some of the valid input strings are
AVG(SUM(1, 2, 3), SUM(4, 5, 6)) * 100
SUM(V1/2,(2+7),3)+(V1+V2)
Can someone please help me on this.
From the comments on the question:
Are you trying to ensure that only valid characters, aggregate functions, and variable names appear in the string or are you attempting to also check that the string is well formatted (i.e. there is an operand on either side of an operator, parenthesis are matched, etc...)?
- D M
#D M I am just trying to validate only for valid characters
- DevMJ
Since you're only looking to check that a formula contains digits, functions, variables, etc (and not that it is also valid for execution), you can add possibilities as alternatives in one group.
One possibility is the pattern ^(?:\d|\+|\-|\/|\*|\(|\)|\.|\,|AVG|SUM|MAX|MIN|V\d+| )*$ which matches the samples you provided.
Try it out!
Explanation:
Token
Matches
^
Start of a line
(?:
Start of the non-capturing group of alternatives
\d
A digit (equivalent to [0-9])
\+
The + character
\-
The - character
\/
The / character
\*
The * character
\(
The ( character
\)
The ) character
\.
The . character
\,
The , character
AVG
The string AVG
SUM
The string SUM
MAX
The string MAX
MIN
The string MIN
V\d+
The V character followed by one or more digits
A space
)
End of the non-capturing group of alternatives
*
Any of the alternatives zero or more times
$
End of a line
As mentioned in the comments, if you also want to check that the string can be executed successfully, you will need to look into defining a context-free grammar for your "language" and using a tool like ANTLR to parse strings using the grammar.
Since all you care for is the valid characters, that's indeed a job for regexes.
A simple way to filter this is just to add letters to the valid characters:
^[A-Z0-9+-/()., ]+$
You can even add a-z if you want to allow lowercase characters as well.

Regex to check time period value 1W, 5Y

Here I need to validate a string like this in C#:
The string's max length: 4
The last character should be any one from D, W, M, Y (representing day,week,month,year)
The rest(initial) all characters should be a non negative number.
Example:
Valid values : "1D", "4w", "26W", "3M","24M","5Y" etc
Invalid values : "M3","360DM","5555D", "1Y2M", "-5Y" etc
You could use the following regular expression (with the case-indifferent flag set).
^(?:0|[1-9]\d{0,2})[DWMY]$
Demo
The regex engine performs the following operations.
^ match the beginning of the string
(?: begin a non-capture group
0 match '0'
| or
[1-9] match a digit other than '0'
\d{0,2} match 0-2 digits
) end non-capture group
[DWMY] match one of the characters indicated
$ match end of string
Bad Question, nontheless that's quite basic for a regex: string pattern = "([0-9]{1-3})([YDWM])"; it's up to you to refine this pattern for case sensitivity. you have multiple choices on how to handle that

Regular expression to accept 5 characters with optional

Hi i have to write a regular expression that should match the format like A12BC. Here first 2 characters that is A & 1 is mandatory and next 3 characters 2, B & C are optional. Currently my regEx works if i give the string value as A12BC.
When I give the input as A1B it should not match but my regular expression matches and gives me the result as susses. Can any one please help me and modify my RegExp so
that it behaves as per below:
Case "A1" : Should match
Case "A1B" : Should not match (this case is not working)
Case "A12B" : Should match
Case "A12BC" : Should match
Case "A12BCD" : Should not match
My regular expression is as below:
^[a-zA-Z][0-9][0-9]?[a-zA-Z]?[a-zA-Z]?$
To make sure that the third character, if present, is a digit, make third character mandatory in an optional group, like this:
^[a-zA-Z][0-9]([0-9][a-zA-Z]?[a-zA-Z]?)?$
This expression says that if the third character is present, it needs to match a digit. The two trailing letters are optional, too.
Note: you can simplify your expression by using predefined Character Classes \w for letters and \d for digits. Remember that you need to double backslashes for use in "plain" string literals (as opposed to verbatim string literals, in which backslashes are not doubled).
You can use:
^[a-zA-Z][0-9](?:[0-9][a-zA-Z]{0,2})?$
In the 2BC pattern, you have to make the digit mandatory before allowing zero, one or two letters.
(?:[0-9][a-zA-Z]{0,2})? matches an empty string, or a digit, or a digit followed by a letter, or a digit followed by two letters, but not a single letter.
(?:...) is a non capturing group, see demo here.

Password Regular Expression Validation

These are the requirements but I guess it's too complicated for my regular expression skills...
. between 6 and 10 alphanum characters
. allowed A-Z,a-z,0-9,#,$,_
. Must begin with a letter
. Must contain at least one number
. cannot contain two consecutive identical characters
. cannot contain two consecutive identical numbers
I know the basic of regular expression such as
[A-Za-Z] = characters only etc... but when it comes to consecutive character and stuff...
Try this
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{6,20})
Description of above Regular Expression:
( # Start of group
(?=.*\d) # must contains one digit from 0-9
(?=.*[a-z]) # must contains one lowercase characters
(?=.*[A-Z]) # must contains one uppercase characters
(?=.*[\W]) # must contains at least one special character
. # match anything with previous condition checking
{6,20} # length at least 6 characters and maximum of 20
) # End of group
"/W" will increase the range of characters that can be used for password and pit can be more safe.
string pattern1 = #"^[a-zA-Z]([a-zA-Z])*"; //start and any number of characters
string pattern2 = #"[0-9]+"; //one number or more numbers
string pattern3 = #"[##$%]*"; // special symbol allowed
string pattern4 = #"(.)\1";//consecutive characters
string pattern5 = #"^(.){6,10}$"; //min max
should you want to validate the password you can use groups to do soo ;
(?<a>[a-zA-Z])?(?<b>[0-9])?(?<c>[#%$#/\\\(\)])?
Will give you a match in any of the 3 groups (a,b and c)
uper and lower characters will be in group a
numeric characters will be in group b
and special characters will be in group c
you can use the regex.match.groups("a").count to see if any characters from group a could be found
if you find characters in all 3 groups, the password is strong.

Restrict the length of a match

What would this C# regex look like?
At least one (1) character in length
Up to seven (7) characters in length
Numeric characters
I have this, but I needs to check for 1-7 digits:
var chequeNumRX = new Regex("^[0-9]+$");
In regular expressions, you can use the repetition operator {min,max}.
var chequeNumRX = new Regex(#"^\d{1,7}$");
The above regex would match \d a minimum of 1 time and a maximum of 7 times.
Note that \d is a shorthand character class equivalent to [0-9].
Just put the range in after your list of charaters:
{1,7} : allows 1 - 7 charaters
e.g
^[0-9]{1,7}$

Categories