简体   繁体   中英

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. 20 letters?

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.

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()

string test = "testing";

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

I hope this helps, good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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