简体   繁体   English

C#:如何检查这些字符串是否仅包含数字和字母? (正则表达式)

[英]C#: How can I check if these strings contain only numbers and letters? (Regex)

so I have a code like this: 所以我有这样的代码:

// 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;
}

Now I have to ask you guys, how can I check, if the string number, age, salary only contains numbers and the string prename, name, place only contains letters from AZ and az and max. 现在我要问你们,我该如何检查string number, age, salary仅包含数字,而string prename, name, place仅包含来自AZ和az和max的字母。 20 letters? 20个字母?

I heard something about Regex but i don't understand it.. Thanks for help :). 我听说过有关正则表达式的内容,但我听不懂..谢谢您的帮助:)。

You can use regex - it is regular expressions that check if string match some pattern. 您可以使用regex-它是用于检查字符串是否与某些模式匹配的正则表达式。

For digits only you can use this regex: 仅对于数字,您可以使用此正则表达式:

^[0-9]+$

For letters only: 仅针对字母:

^[A-Za-z]{1,20}$

So, your code should be like this (digits example): 因此,您的代码应如下所示(数字示例):

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");
}

for the length of the string you can use the method .length() 对于字符串的长度,可以使用.length()方法

string test = "testing";

if(test.length() <=  20){}

I hope this helps, good luck 希望对您有帮助,祝您好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM