[英]How to check the string has specific set of character in it or not?
我需要檢查輸入的字符串是否包含任何字符,並且-在開始時?
示例代碼是:
string name = "e-rob";
if (name.Contains("[a-z]-"))
{
Console.WriteLine(name);
}
else
{
Console.WriteLine("no match found");
}
Console.ReadLine();`
上面的代碼不起作用。 它不一定是-始終可以是任何字符,然后-
我怎樣才能做到這一點?
嘗試使用一些RegEx:
Regex reg = new Regex("^[a-zA-Z]-");
bool check = reg.IsMatch("e-rob");
或更簡潔:
if (Regex.IsMatch("e-rob", "^[a-zA-Z]-")) {
// do stuff for when it matches here
}
神奇的地方是^[a-zA-Z]
。 逐段分解:
^
:告訴它從檢查模式的開頭開始
[a-zA-Z]
:告訴它檢查A和Z之間的一個大寫或小寫字母
-
:告訴它在字母后直接檢查“-”字符
因此e-rob
或E-rob
都將返回true,而abcdef-g
將返回false
另外,請注意,要使用RegEx,您需要包括
using System.Text.RegularExpressions;
在您的課程文件中
這是一個很好的鏈接,可以教您一些有關RegEx的信息,這是有史以來討論匹配模式時最好的工具
試試正則表達式
Regex reg = new Regex("[a-z]-");
if(reg.IsMatch(name.SubString(0, 2))
{...}
另一種方法是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.