字符串的正则表达式以Alphabet开头,字母后面有空格

时间:2013-05-28 10:31:09

标签: c# regex string

我需要一个正则表达式来执行以下操作

示例:string checker=" A Cat has catched the mouse"

正则表达式应该确保第一个字符应该是字母A-D,并且后面应该有一个空格。

我尝试了正则表达式@"^[A]",但它也与下面的字符串匹配:

string checker="At the speed of blah blah blah"

所以这个正则表达式并不能满足我的需要。

3 个答案:

答案 0 :(得分:2)

模式:^[A-D] .*(即string pattern = @"^[A-D] .*")将匹配以首字母ABC或{{中的一个字母开头的字符串1}}然后是空格。

注意:如果您只进行验证,则可以省略D(即使用.*^[A-D])模式)部分来自模式。

答案 1 :(得分:2)

也许这有帮助^([A-D] )

var checkers = new string[] {"At the speed of blah blah blah", "A the speed of blah blah blah", "B the speed of blah blah blah",
                            "C the speed of blah blah blah", "D the speed of blah blah blah", "Dt the speed of blah blah blah",
                            "E the speed of blah blah blah"};

var regex = @"^([A-D] )";

foreach (var checker in checkers)
{
    var matches = Regex.Match(checker, regex);
    Console.WriteLine (matches.Success);
}

输出:

False
True
True
True
True
False
False

答案 2 :(得分:1)

尝试使用此表达式

@"^[A-D]\s"

如果你需要捕获整个文本,你应该

@"^[A-D]\s.*"