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

本文关键字:有一个 空格 开头 字符串 正则表达式 | 更新日期: 2023-09-27 18:15:36

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

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

正则表达式应该确保第一个字符应该是大写字符a - d,并且后面应该有一个空格。

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

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

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

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

也许这对^([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

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

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

尝试使用这个表达式

@"^[A-D]'s"

如果您需要捕获整个文本,您应该执行

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