I try to create an regex in C# for allow only string with more than 3 char BUT if it starts with 'sch' it schould have a minimal length of 6 and if it starts with 'st' or 'ch' it should have a minimal length of 5.
The second part is pritty easey but the first part (all others length of 3) is more complicated:
"(^(SCH).{3})|(^(ST).{3})|(^(CH).{3})|^(!SCH).{3}"
Thanks for your help!
Seems like you want something like this,
#"^SCH.{3,}|^(?:ST|CH).{3,}|^(?!S?CH|ST).{3,}"
{3,} in .{3,} would repeat the previous token that is . (which matches any character) 3 or more times.
DEMO
^(?!S?CH|ST).{3,} if the string doesn't startswith SCH or ST or CH, then match those strings only if it has at-least three characters.
Personally I wouldn't use a regex for that. Just use standard string operations.
bool IsValid(string str)
{
if(str.StartsWith("st") || str.StartsWith("ch"))
return str.Length >= 5;
if(str.StartsWIth("sch"))
return str.Length >= 6;
return str.Length > 3;
}
How do I use for example this line:
Regex.Matches(str,#"[a-zA-Z]");
that instead of the str I will have a char?
It seems that you want to test if a character is a letter. You do not need a regular expression to do that. Instead you can use the following:
var isLetter = Char.IsLetter(ch);
However, this will return true for all UNICODE letters, not only A-Z, e.g. also accented letters like É or other letters like Æ and 你.
If you want to only test for A-Z (upper and lower case) you can use this simple test:
var upperCaseCh = Char.ToUpperInvariant(ch);
var isLetter = 'A' <= upperCaseCh && upperCaseCh <= 'Z';
I'd rather use the static functions of the char class or use the comparison operators, i.e.
var test = 'a' <= c && c <= 'z';
The static methods can give you the character class, e.g. letter, digit or whitespace.
You can call ToString on character and then use that like:
char ch = 'c';
Regex.Matches(ch.ToString(),#"[a-zA-Z]");
I would like to check, in C#, if a char contains a non-ASCII character. What is the best way to check for special characters such as 志 or Ω?
ASCII ranges from 0 - 127, so just check for that range:
char c = 'a';//or whatever char you have
bool isAscii = c < 128;
bool HasNonASCIIChars(string str)
{
return (System.Text.Encoding.UTF8.GetByteCount(str) != str.Length);
}
Just in case anybody comes across this. In dotNET6 there is a new method to check whether a character is an ASCII character or not
public static bool IsAscii (char c);
To solve the issue, you can just write
var containsOnlyAscii = str.All(char.IsAscii);
using the LINQ All method.
In general, you can use this new method to check individual characters
var isAscii = char.IsAscii(c);
I want to take a string and check the first character for being a letter, upper or lower doesn't matter, but it shouldn't be special, a space, a line break, anything. How can I achieve this in C#?
Try the following
string str = ...;
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);
Try the following
bool isValid = char.IsLetter(name.FirstOrDefault());
return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')
You should look up the ASCII table, a table which systematically maps characters to integer values. All lower-case characters are sequential (97-122), as are all upper-case characters (65-90). Knowing this, you do not even have to cast to the int values, just check if the first char of the string is within one of those two ranges (inclusive).
I read a string from the console. How do I make sure it only contains English characters and digits?
Assuming that by "English characters" you are simply referring to the 26-character Latin alphabet, this would be an area where I would use regular expressions: ^[a-zA-Z0-9 ]*$
For example:
if( Regex.IsMatch(Console.ReadLine(), "^[a-zA-Z0-9]*$") )
{ /* your code */ }
The benefit of regular expressions in this case is that all you really care about is whether or not a string matches a pattern - this is one where regular expressions work wonderfully. It clearly captures your intent, and it's easy to extend if you definition of "English characters" expands beyond just the 26 alphabetic ones.
There's a decent series of articles here that teach more about regular expressions.
Jørn Schou-Rode's answer provides a great explanation of how the regular expression presented here works to match your input.
You could match it against this regular expression: ^[a-zA-Z0-9]*$
^ matches the start of the string (ie no characters are allowed before this point)
[a-zA-Z0-9] matches any letter from a-z in lower or upper case, as well as digits 0-9
* lets the previous match repeat zero or more times
$ matches the end of the string (ie no characters are allowed after this point)
To use the expression in a C# program, you will need to import System.Text.RegularExpressions and do something like this in your code:
bool match = Regex.IsMatch(input, "^[a-zA-Z0-9]*$");
If you are going to test a lot of lines against the pattern, you might want to compile the expression:
Regex pattern = new Regex("^[a-zA-Z0-9]*$", RegexOptions.Compiled);
for (int i = 0; i < 1000; i++)
{
string input = Console.ReadLine();
pattern.IsMatch(input);
}
The accepted answer does not work for the white spaces or punctuation. Below code is tested for this input:
Hello: 1. - a; b/c \ _(5)??
(Is English)
Regex regex = new Regex("^[a-zA-Z0-9. -_?]*$");
string text1 = "سلام";
bool fls = regex.IsMatch(text1); //false
string text2 = "123 abc! ?? -_)(/\\;:";
bool tru = regex.IsMatch(text2); //true
One other way is to check if IsLower and IsUpper both doesn't return true.
Something like :
private bool IsAllCharEnglish(string Input)
{
foreach (var item in Input.ToCharArray())
{
if (!char.IsLower(item) && !char.IsUpper(item) && !char.IsDigit(item) && !char.IsWhiteSpace(item))
{
return false;
}
}
return true;
}
and for use it :
string str = "فارسی abc";
IsAllCharEnglish(str); // return false
str = "These are english 123";
IsAllCharEnglish(str); // return true
Do not use RegEx and LINQ they are slower than the loop by characters of string
Performance test
My solution:
private static bool is_only_eng_letters_and_digits(string str)
{
foreach (char ch in str)
{
if (!(ch >= 'A' && ch <= 'Z') && !(ch >= 'a' && ch <= 'z') && !(ch >= '0' && ch <= '9'))
{
return false;
}
}
return true;
}
do you have web access? i would assume that cannot be guaranteed, but Google has a language api that will detect the language you pass to it.
google language api
bool onlyEnglishCharacters = !EnglishText.Any(a => a > '~');
Seems cheap, but it worked for me, legit easy answer.
Hope it helps anyone.
bool AllAscii(string str)
{
return !str.Any(c => !Char.IsLetterOrDigit(c));
}
Something like this (if you want to control input):
static string ReadLettersAndDigits() {
StringBuilder sb = new StringBuilder();
ConsoleKeyInfo keyInfo;
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter) {
char c = char.ToLower(keyInfo.KeyChar);
if (('a' <= c && c <= 'z') || char.IsDigit(c)) {
sb.Append(keyInfo.KeyChar);
Console.Write(c);
}
}
return sb.ToString();
}
If i dont wnat to use RegEx, and just to provide an alternate solution, you can just check the ASCII code of each character and if it lies between that range, it would either be a english letter or a number (This might not be the best solution):
foreach (char ch in str.ToCharArray())
{
int x = (int)char;
if (x >= 63 and x <= 126)
{
//this is english letter, i.e.- A, B, C, a, b, c...
}
else if(x >= 48 and x <= 57)
{
//this is number
}
else
{
//this is something diffrent
}
}
http://en.wikipedia.org/wiki/ASCII for full ASCII table.
But I still think, RegEx is the best solution.
I agree with the Regular Expression answers. However, you could simplify it to just "^[\w]+$". \w is any "word character" (which translates to [a-zA-Z_0-9] if you use a non-unicode alphabet. I don't know if you want underscores as well.
More on regexes in .net here: http://msdn.microsoft.com/en-us/library/ms972966.aspx#regexnet_topic8
As many pointed out, accepted answer works only if there is a single word in the string. As there are no answers that cover the case of multiple words or even sentences in the string, here is the code:
stringToCheck.Any(x=> char.IsLetter(x) && !((int)x >= 63 && (int)x <= 126));
<?php
$string="हिन्दी";
$string="Manvendra Rajpurohit";
echo strlen($string); echo '<br>';
echo mb_strlen($string, 'utf-8');
echo '<br>';
if(strlen($string) != mb_strlen($string, 'utf-8'))
{
echo "Please enter English words only:(";
}
else {
echo "OK, English Detected!";
}
?>