简体   繁体   中英

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:

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,

i have tried to achieve this with Regex but with no success.

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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