سؤال

I have a requirement to check wether the incoming string has any character and - in the begining?

sample code is:

        string name = "e-rob";
        if (name.Contains("[a-z]-"))
        {
            Console.WriteLine(name);
        }
        else
        {
            Console.WriteLine("no match found");
        }
        Console.ReadLine();`

The above code is not working. It is not neccessarily e- all the time it could be any character and then -

How can I do this?

هل كانت مفيدة؟

المحلول

Try using some RegEx:

Regex reg = new Regex("^[a-zA-Z]-");
bool check = reg.IsMatch("e-rob");

Or even more concise:

if (Regex.IsMatch("e-rob", "^[a-zA-Z]-")) {
    // do stuff for when it matches here
}

The ^[a-zA-Z] is where the magic happens. Breaking it down piece-by-piece:


^: tells it to start at the beginning of whatever it's checking the pattern against

[a-zA-Z]: tells it to check for one upper- or lower-case letter between A and Z

-: tells it to check for a "-" character directly after the letter


So e-rob or E-rob would both return true where abcdef-g would return false

Also, as a note, in order to use RegEx you need to include

using System.Text.RegularExpressions;

in your class file

Here's a great link to teach you a bit about RegEx which is the best tool ever when you're talking about matching patterns

نصائح أخرى

Try Regex

Regex reg = new Regex("[a-z]-");
if(reg.IsMatch(name.SubString(0, 2))
{...}

Another way to do this, kind of LINQish:

StartsWithLettersOrDash("Test123");

public bool StartsWithLettersOrDash(string str)
{
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char [] alphas = (alphabet + alphabet.ToLower()).ToCharArray();
    return alphas.Any(z => str.StartsWith(z.ToString() + "-"));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top