Special letters check - c#

How can I check if a TextBox contains numbers, letters, and also have special letters like "õ, ä, ö, ü"?
I use code to check numbers and letters:
Regex.IsMatch(Value, "^[a-z0-9]+$", RegexOptions.IgnoreCase)

How can I check if textbox contains numbers and letters only,
bool isValid = textBox.Text.All(char.IsLetterOrDigit);
Consider the following example:
string str = "Something123õäö";
bool isValid = str.All(char.IsLetterOrDigit);
You will get true for the above case.

Does How can you strip non-ASCII characters from a string? (in C#) contain any pointers?
You could include the unicode using the \uXXXX syntax within the regex for any additional letters you specifically want to strip test for.
Regex.IsMatch(Value, "^[a-z0-9\u00c0-\u00f6]+$", RegexOptions.IgnoreCase)

Just loop over every char and compare with or to the other chars and with char.GetUnicodeCategory for letters and digits:
var allowed = new[] { 'ö', 'ä' };
var isOK = textBox1.Text.All(c =>
char.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter ||
char.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter ||
char.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber ||
allowed.Contains(c));
UnicodeCategory.LowercaseLetter are standard lowercase letters ('a'..'z'), UnicodeCategory.UppercaseLetter are uppercase letters, and UnicodeCategory.DecimalDigitNumber are digits, so this and a customized allowed array should take care of everything you want to accept.

If you want to validate all "word charters" just use \w if you want to see if a whole string is just word characters or digits use the regex ^(\w|\d)+$

Related

How to check if input string value contains x elements on the right and x elements on left

I am trying to make a catch exception for input string for example
if user enters
123test456
the program to say
The first 3 characters must be letter
so it should accept
wowTest456
You can use Take(), with .All() including letter condition,
var validString = inputString
.Take(3)
.All(x => Char.IsLetter(x));
You can solve it using Regex too. Credit to #JohnathanBarclay.
bool isInvalidString = Regex.IsMatch(inputString, #"^\d{3}");
Explanation:
^ : Matches the beginning of the string
\d: Matches the digit characters
{3} : Matches 3 tokens.
To make it positive regex just check \w instead of \d
bool validString = Regex.IsMatch(inputString, #"^\w{3}");
Using \w includes _(underscore) as well, if you don't want _ as a part of first three letters, then you can use range like below
bool validString = Regex.IsMatch(inputString, #"^[a-zA-Z]{3}");
Try Online

C#: How can I only return the first set of capital letter words from a string?

If I wanted to parse back a string to only return the first all capital words in it how would I do that?
Example:
"OTHER COMMENTS These are other comments that would be here. Some more
comments"
I want to just return "OTHER COMMENTS"
These first upper case words can be many and the exact count is
unknown.
There could be other words in the string after with all caps
that I just want to ignore.
You can use a combination of Split (to break the sentence into words), SkipWhile (to skip words that aren't all caps), ToUpper (to test the word against it's upper-case counterpart), and TakeWhile (to take all sequential upper-case words once one is found). Finally, these words can be re-joined using Join:
string words = "OTHER COMMENTS These are other comments that would be here. " +
"Some more comments";
string capitalWords = string.Join(" ", words
.Split()
.SkipWhile(word => word != word.ToUpper())
.TakeWhile(word => word == word.ToUpper()));
You can loop through the string as an array of chars. To check if the char is uppercase, use Char.IsUpper https://www.dotnetperls.com/char-islower. So, in the loop you can say if its a char - set a flag that we started reading the set. Then add that char to a collection of chars. Keep looping and once it is no longer an upper case char and the flag is still true, break out of the loop. Then return the collection of chars as a string.
Hope that helps.
var input = "OTHER COMMENTS These are other comments that would be here. Some more comments";
var output = String.Join(" ", input.Split(' ').TakeWhile(w => w.ToUpper() == w));
Split it into words, then take words while the uppercase version of the word is the same as the word. Then combine them back with the space separator.
You could also use Regex:
using System.Text.RegularExpressions;
...
// The Regex pattern is any number of capitalized letter followed by a non-word character.
// You may have to adjust this a bit.
Regex r = new Regex(#"([A-Z]+\W)+");
string s = "OTHER COMMENTS These are other comments that would be here. Some more comments";
MatchCollection m = r.Matches(s);
// Only return the first match if there are any matches.
if (m.Count > 0)
{
Console.WriteLine(r.Matches(s)[0]);
}

Find multiple, non consecutive, occurrences of a character in string

Can somebody please help me write RegEx expression which can check if a string contains more than one occurrence of a uppercase (or lowercase, doesn't matter) letter but not in a row.
I need to have at least two (or even better n) occurrences in a string. If n=2 valid situations would be PassWord or PAssword or PASSWord.
When I tried this /(?=([A-Z]{2,3}))/g it matched PassWOrd but not PassWord.
What is strange to me is that it also matched PaSSWOrd. I thought 3 in {2,3} actually means that no more that 3 Uppercase characters will be matched. Why is SSWO matched?
I tried similar variations but non of them worked for me (nothing strange as i'm not very familiar with RegEx).
Can this be done using RegEx?
The (?=([A-Z]{2,3})) regex matches 2 to 3 consecutive uppercase ASCII letters anywhere inside a string. You want to match a string that only contains 2 to 3 uppercase ASCII letters, not necessarily consecutively.
To match a string that only contains two uppercase ASCII letters (no more no less), use the following expression:
^(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
Or, if you only allow ASCII letters in the whole string:
^(?:[a-z]*[A-Z]){2}[a-z]*$
See the regex demo.
Pattern details
^ - start of string
(?:[^A-Z]*[A-Z]){2} - exactly 2 consequent occurrences of
[^A-Z]* - zero or more chars other than ASCII uppercase letters
[A-Z] - one ASCII uppercase letter
[^A-Z]* - zero or more chars other than ASCII uppercase letters
$ - end of string.
In C#, use
var strs = new List<string> { "PassWord", "PAssword", "PASSWord"};
var n = 2;
var pat = $#"^(?:[^A-Z]*[A-Z]){{{n}}}[^A-Z]*$";
foreach (var s in strs) {
Console.WriteLine("{0}: {1}", s, Regex.IsMatch(s, pat));
}
Result:
PassWord: True
PAssword: True
PASSWord: False
See the online demo
Note that in case you need to require 2 uppercase ASCII letters in a string where other chars can be any chars, you do not need a regex, use LINQ:
var strs = new List<string> { "PassWord", "PAssword", "PASSWord"};
var n = 2;
foreach (var s in strs) {
var res = s.Count(c => (c >= 65 && c <= 90));
Console.WriteLine("{0}: {1}", s, res == 2);
}
See another demo. The .Count(c => (c >= 65 && c <= 90)) part will count the uppercase ASCII letters anywhere in the string, and res==2 will return a boolean result, whether the number is equal to 2 or not. It can be adjusted for a numeric range check easily.
If you need Unicode compatibility, replace .Count(c => (c >= 65 && c <= 90)) with .Where(Char.IsUpper).

How to find out if a string contains digits followed by alphabet characters?

How can I find out whether a given string contains at least one number followed by alphabets using Regex in c#?
For example :
var strInput="Test123Test";
The function should return a bool value.
result = Regex.IsMatch(subjectString, #"\d\p{L}");
will return True for your sample string. Currently, this regex also considers non-ASCII digits and letters as valid matches, if you don't want that, use #"[0-9][A-Za-z])" instead.
If you want to match 123 only then:-
Match m = Regex.Match("Test123Test", #"(\p{L}+)(\d+)") ;
string result = m.Groups[2].Value
If you want to get the bool value then do this:-
Console.WriteLine(!String.IsNullOrEmtpty(result))) ;
or simple use:-
Regex.IsMatch("Test123Test", #"\p{L}+\d+") ;
Try this:
if(Regex.IsMatch(strInput, #"[0-9][A-Za-z]"))
...

Regular Expression For Alphanumeric String With At Least One Alphabet Or Atleast One Numeric In The String

To test one alphanumeric string we usually use the regular expression "^[a-zA-Z0-9_]*$" (or most preferably "^\w+$" for C#). But this regex accepts numeric only strings or alphabet only strings, like "12345678" or "asdfgth".
I need one regex which will accept only the alphanumeric strings that have at-least one alphabet and one number. That is to say by the regex "ar56ji" will be one of the correct strings, not the previously said strings.
Thanks in advance.
This should do it:
if (Regex.IsMatch(subjectString, #"
# Match string having one letter and one digit (min).
\A # Anchor to start of string.
(?=[^0-9]*[0-9]) # at least one number and
(?=[^A-Za-z]*[A-Za-z]) # at least one letter.
\w+ # Match string of alphanums.
\Z # Anchor to end of string.
",
RegexOptions.IgnorePatternWhitespace)) {
// Successful match
} else {
// Match attempt failed
}
EDIT 2012-08-28 Improved efficiency of lookaheads by changing the lazy dot stars to specific greedy char classes.
Try this out:
"^\w*(?=\w*\d)(?=\w*[a-zA-z])\w*$"
There is a good article about it here:
http://nilangshah.wordpress.com/2007/06/26/password-validation-via-regular-expression/
This should work:
"^[a-zA-Z0-9_]*([a-zA-Z][0-9]|[0-9][a-zA-Z])[a-zA-Z0-9_]*$"
This will match:
<zero-or-more-stuff>
EITHER <letter-followed-by-digit> OR <digit-followed-by-letter>
<zero-or-more-stuff>
By ensuring you have either a digit followed by letter or a letter followed by digit, you are enforcing the requirement to have at least one digit and at least one letter. Note that I've left out the _ above, because it wasn't clear whether you would accept that as a letter, a digit, or neither.
Try this one ^([a-zA-z]+[0-9][a-zA-Z0-9]*)|([0-9]+[a-zA-z][a-zA-Z0-9]*)$
Simple is better. If you had a hard time writing it originally, you're (or some other poor sap) is going to have a hard time maintaining it or modifying it. (And I think that I see some possible holes in the approaches listed above.)
using System.Text.RegularExpressions;
boolean IsGoodPassword(string pwd){
int minPwdLen = 8;
int maxPwdLen = 12;
boolean allowableChars = false;
boolean oneLetterOneNumber = false;
boolean goodLength = false;
string allowedCharsPattern = "^[a-z0-9]*$";
//Does it pass the test for containing only allowed chars?
allowableChars = Regex.IsMatch(pwd, allowedCharsPattern , RegexOptions.IgnoreCase));
//Does it contain at least one # and one letter?
oneLetterOneNumber = Regex.IsMatch(pwd, "[0-9]")) && Regex.IsMatch(pwd, "[a-z]", RegularExpressions.IgnoreCase));
//Does it pass length requirements?
goodLength = pwd.Length >= minPwdLength && pwd.Length <= maxPwdLength;
return allowableChars && oneLetterOneNumber && goodLength;
}

Categories

Resources