简体   繁体   English

在C#中构建正则表达式

[英]Building regex expression in c#

I have some string like this one: 我有一些像这样的字符串:

DEV_NUM_26 - Some type...TYPE0 with support of some functions DEV_NUM_26-某些类型... TYPE0,具有某些功能的支持

My target is to get next data: (id=26, type=TYPE0) 我的目标是获取下一个数据: (id = 26,type = TYPE0)

Expression is looks like this: 表达式看起来像这样:

    (?<id>(?<=DEV_NUM_) \d{0,3}) \s-\s (?<name>(?<=Some \s type \.+) \w+)

but I got 0 match results and the problem is in second (?<=). 但是我得到0个匹配结果,问题出在秒(?<=)。 If I try to make something like: 如果我尝试做类似的事情:

    (?<id>(?<=DEV_NUM_) \d{0,3}) \s-\s (?<name>Some \s type \.+ \w+)

I got next result: (id=26, type=Some type...TYPE0) . 我得到了下一个结果: (id = 26,type = Some type ... TYPE0)

The first and main question is how to fix this expression) And last but not least is why excluding prefix (?<=) doesn't work at the end of expression? 第一个也是主要的问题是如何修复该表达式)最后但并非最不重要的一点是,为什么排除前缀(?<=)在表达式末尾不起作用? As I understand, it suppose to find a part of expression in brackets and ignore it, like in the first part of expression, but it doesn't... 据我了解,它假定在方括号中找到表达式的一部分并忽略它,就像在表达式的第一部分中一样,但是并没有...

Instead, place the parts you don't want to include outside of your named capturing groups. 而是将不想包含的部分放在命名的捕获组之外。 Note: I removed the Positive Lookbehind assertions from your expression because they are really not necessary here. 注意:我从表达式中删除了正向隐式断言,因为在这里实际上并不需要它们。

String s = "DEV_NUM_26 - Some type...TYPE0 with support of some functions";
Match m  = Regex.Match(s, @"DEV_NUM_(?<id>\d{0,3})\s-\sSome\stype\.+(?<name>\w+)");
if (m.Success)
    Console.WriteLine(m.Groups["id"].Value);   //=> "26"
    Console.WriteLine(m.Groups["name"].Value); //=> "TYPE0"

If you want to shorten your expression, you could write it as ... 如果您想缩短表情,可以将其写为...

@"(?x)DEV_NUM_ (?<id>\d+) [^.]+\.+ (?<name>\w+)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM