[英]C#: How can I check if these strings contain only numbers and letters? (Regex)
所以我有這樣的代碼:
// Add new adress
static int New(ref List<string> adr, int index)
{
Console.Write("Nubmer "); string number= Console.ReadLine();
Console.Write("Prename"); string prename= Console.ReadLine();
Console.Write("Name"); string name= Console.ReadLine();
Console.Write("Place "); string place= Console.ReadLine();
Console.Write("Age "); string age= Console.ReadLine();
Console.Write("Salary "); string salary= Console.ReadLine();
Console.Write("\nDatensatz speichern? <j/n> "); string wahl = Console.ReadLine().ToUpper();
if (wahl == "J")
{
string zeile = number + ";" + prename + ";" + name + ";" + place + ";" + age + ";" + salary ;
adr.Add(zeile);
File.WriteAllLines(@filename, adr);
index++;
}
return index;
}
現在我要問你們,我該如何檢查string number, age, salary
僅包含數字,而string prename, name, place
僅包含來自AZ和az和max的字母。 20個字母?
我聽說過有關正則表達式的內容,但我聽不懂..謝謝您的幫助:)。
您可以使用regex-它是用於檢查字符串是否與某些模式匹配的正則表達式。
僅對於數字,您可以使用此正則表達式:
^[0-9]+$
僅針對字母:
^[A-Za-z]{1,20}$
因此,您的代碼應如下所示(數字示例):
using System.Text.RegularExpressions; //on the top
string regexPattern = "^[0-9]+$";
string testString = "123456";
if (Regex.IsMatch(testString, regexPattern))
{
Console.WriteLine("String contains only digits and is valid");
}
else
{
Console.WriteLine("String contains symbols other than digits or is empty or too long");
}
對於字符串的長度,可以使用.length()方法
string test = "testing";
if(test.length() <= 20){}
希望對您有幫助,祝您好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.