简体   繁体   English

正则表达式无法正常工作

[英]Regex not working as expected

ok so let me explain the current situation: 好的,让我解释一下当前情况:

i get some strings from COM1, i filtered this to show only the needed information and thus i have only strings like this: 我从COM1获得了一些字符串,我对此进行了过滤以仅显示所需的信息,因此我只有这样的字符串:

NTF,IDAS,RXSTAT,IND,01-0100,01-0131,+,-63,81

now the problem is that in this example i need to get the number: 131 and ONLY that number, 现在的问题是,在此示例中,我需要获取数字:131,仅该数字,

i have tried to achieve this with Regex but with no success. 我试图用Regex实现此目的,但没有成功。

i have this as my Regex: 我有这个作为我的正则表达式:

Regex.Match(line, ",01-0100,01-0([0-9]{3})").Value.ToString()

and expect that to return me the 并期望能给我回报

131

but instead it returns: 但是它返回:

,01-0100,01-0131

can anybody help me with this problem? 有人可以帮助我解决这个问题吗?

You are using the wrong group index. 您使用了错误的组索引。 Group 0 is the entire match, group 1 is the value for the first group. 组0是整个匹配项,组1是第一个组的值。

Regex.Match(line, ",01-0100,01-0([0-9]{3})").Groups[1].Value.ToString()

You could also name your group: 您还可以命名您的群组:

Regex.Match(line, ",01-0100,01-0(?<mygroup>[0-9]{3})").Groups["mygroup"].Value.ToString()

Oh, and as a group's value is always a string: 哦,作为一个组的值始终是一个字符串:

Regex.Match(line, ",01-0100,01-0(?<mygroup>[0-9]{3})").Groups["mygroup"].Value;

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

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