Capturing a repeated group

后端 未结 9 1527
[愿得一人]
[愿得一人] 2021-01-14 09:17

I am attempting to parse a string like the following using a .NET regular expression:

H3Y5NC8E-TGA5B6SB-2NVAQ4E0

and return the following u

相关标签:
9条回答
  • 2021-01-14 09:32

    Mike,

    You can use character set of your choice inside character group. All you need is to add "+" modifier to capture all groups. See my previous answer, just change [A-Z0-9] to whatever you need (i.e. [ABCDEFGHJKLMNPQRSTVXYZ0123456789])

    0 讨论(0)
  • 2021-01-14 09:36

    You can use this pattern:

    Regex.Split("H3Y5NC8E-TGA5B6SB-2NVAQ4E0", "([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}+)-?")
    

    But you will need to filter out empty strings from resulting array. Citation from MSDN:

    If multiple matches are adjacent to one another, an empty string is inserted into the array.

    0 讨论(0)
  • 2021-01-14 09:45

    After reviewing your question and the answers given, I came up with this:

    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex(@"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})", options);
    string input = @"H3Y5NC8E-TGA5B6SB-2NVAQ4E0";
    
    MatchCollection matches = regex.Matches(input);
    for (int i = 0; i != matches.Count; ++i)
    {
        string match = matches[i].Value;
    }
    

    Since the "-" is optional, you don't need to include it. I am not sure what you was using the {4} at the end for? This will find the matches based on what you want, then using the MatchCollection you can access each match to rebuild the string.

    0 讨论(0)
提交回复
热议问题