我正在尝试学习使用.net核心的正则表达式。特别是,我试图使用它们来解析程序集中的嵌入式资源列表,如下所示。
正则表达式模式
^([\w\._])*((?<create>\.Postgres.Create\.)|(?<drop>\.Postgres.Drop\.)([\w\._]))*$
从嵌入式资源列表生成的示例文本
Mynamespace.Postgresql.Create.select_course_units.sql
Mynamespace.Postgresql.Drop.drop_select_course_units.sql
Mynamespace.Postgresql.Create.select_units.sql
Mynamespace.Postgresql.Drop.drop_select_units.sql
...正则表达式有两个命名的捕获组,分别用于Postgres.Create和Postgres.Drop捕获。我的正则表达式找到了这两个匹配项,但是在创建或删除组的捕获中没有存储任何内容。是否有可能让它存储捕获,以便确定匹配是包含创建还是删除?
public void ReadCreateStoredProcedures()
{
const string pattern = @"^([\w\._])*((?<create>\.Postgres.Create\.)|(?<drop>\.Postgres.Drop\.)([\w\._]))*$";
Regex rx = new Regex(pattern, RegexOptions.Compiled | RegexOptions.Multiline);
string[] resNames = typeof(CourseContext).Assembly.GetManifestResourceNames();
string text = string.Join("\n",resNames);
MatchCollection matches = rx.Matches(text);
foreach(Match match in matches)
{
Console.WriteLine($"Matched{match.Value}");
GroupCollection col = match.Groups;
int lC = col["create"].Length;
int lD = col["drop"].Length;
Console.WriteLine($"Total Create Captures : {lC}");
Console.WriteLine($"Total Drop Captures : {lD}");
foreach(var capture in col["create"].Captures)
{
Console.WriteLine($"Create Capture :: {@capture}");
}
foreach (var capture in col["drop"].Captures)
{
Console.WriteLine($"Drop Capture :: {@capture}");
}
}
}发布于 2020-02-22 17:02:53
在您的模式中,您不会获得命名捕获组中的值,因为开始时的这个部分([\w\._])*将一直匹配到字符串的末尾。
您确实获得了一个捕获组(而不是命名捕获组),其中一个字符是字符串的最后一个字符,因为当重复捕获的组时,该组将包含最后一个迭代的值。
下面是一个可选部分((?<create>\.Postgres.Create\.))*$。由于它是可选的,所以模式可以断言字符串的下面一端,并且命名捕获组不包含值。
注意到,\w也匹配下划线,您不必转义字符类中的点
如果您想从Postgresql开始捕获这两个值,可以使用2捕获组,例如:
^\w+\.(?:(?<create>Postgresql\.Create(?:\.\w+)+)|(?<drop>Postgresql\.Drop(?:\.\w+)+))$解释
^开始\w+\.匹配1+单词字符(?:非捕获群(?<create>命名为create Postgresql\.Create(?:\.\w+)+ Match Postgresql.Create and repeat matching a.`和1+字词
- `)` Close group
- `|` Or
- `(?<drop>` Named group `drop`
- `Postgresql\.Drop(?:\.\w+)+` Same as above for Postgresql.Drop
- `)` Named group `drop`
)闭非捕获群$末端.NET regex演示 (单击Table选项卡)
https://stackoverflow.com/questions/60352339
复制相似问题