简体   繁体   English

如何检查字符串中是否包含特定字符集?

[英]How to check the string has specific set of character in it or not?

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:

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. 神奇的地方是^[a-zA-Z] 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 [a-zA-Z] :告诉它检查A和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 因此e-robE-rob都将返回true,而abcdef-g将返回false

Also, as a note, in order to use RegEx you need to include 另外,请注意,要使用RegEx,您需要包括

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 这是一个很好的链接,可以教您一些有关RegEx的信息,这是有史以来讨论匹配模式时最好的工具

Try Regex 试试正则表达式

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

Another way to do this, kind of LINQish: 另一种方法是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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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