如何声明用于继承(类childclass:baseclass)类型的正则表达式?

时间:2019-04-05 06:42:48

标签: c# regex

如何在正则表达式中声明继承格式?

我尝试了下面指定的所有情况,但Regex.IsMatch始终返回false

class \w\W+[:\s\w,]+
class \w+[\s?][\s:[\s?]\w,]+
class \w\s+[\s:\s\w]

我需要为继承设置正则表达式(class childclass:baseclass),格式应返回true(Regex.IsMatch),对于以下测试用例返回false:

公共类childclass:基类

2 个答案:

答案 0 :(得分:0)

请尝试this正则表达式

(公共|私有|内部|受保护)(部分) \ s class \ s +(/ *。 * /) \ s \ w + [\ s] \ s +(/ *。 * /) \ s :\ s +(/ *。 * /) \ s * \ s *(\ w +,* \ w +)

答案 1 :(得分:0)

满足您的条件的简单模式示例:\w+ class \w+ : \w+(一个词,类关键字,类名称,冒号,基类名称)。

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var input = @"
using System;

public class ChildClass : BaseClass
{
}
";
        var pattern = @"\w+ class \w+ : \w+";
        var isMatch = Regex.IsMatch(input, pattern);
        var matches = Regex.Matches(input, pattern);

        Console.WriteLine(isMatch);
        Console.WriteLine(matches.Count);
        Console.WriteLine(matches[0]);
    }
}

输出:

True
1
public class ChildClass : BaseClass

https://dotnetfiddle.net/K9RNbJ