0

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

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

正则表达式应该确保第一个字符应该是一个字母字符 AD 并且在它之后应该有一个空格。

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

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

所以这个正则表达式没有给我我需要的东西。

4

3 回答 3

2

模式:^[A-D] .*(ie string pattern = @"^[A-D] .*") 将匹配以大写字母 、 或 中的一个字母开头A并后跟B空格的字符串。CD

注意:如果您只是进行验证,您可以从模式中省略.*(即使用^[A-D]( string pattern = @"^[A-D] ") 模式)部分。

于 2013-05-28T10:36:25.440 回答
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
于 2013-05-28T10:40:00.220 回答
1

试试这个表达式

@"^[A-D]\s"

如果您需要捕获整个文本,您应该这样做

@"^[A-D]\s.*"
于 2013-05-28T10:34:20.373 回答