Capturing a repeated group

后端 未结 9 1526
[愿得一人]
[愿得一人] 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:19

    What are the defining characteristics of a valid block? We'd need to know that in order to really be helpful.

    My generic suggestion, validate the charset in a first step, then split and parse in a seperate method based on what you expect. If this is in a web site/app then you can use the ASP Regex validation on the front end then break it up on the back end.

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

    If you're just checking the value of the group, with group(i).value, then you will only get the last one. However, if you want to enumerate over all the times that group was captured, use group(2).captures(i).value, as shown below.

    system.text.RegularExpressions.Regex.Match("H3Y5NC8E-TGA5B6SB-2NVAQ4E0","(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]+)-?)*").Groups(2).Captures(i).Value
    
    0 讨论(0)
  • 2021-01-14 09:24

    I have discovered the answer I was after. Here is my working code:

        static void Main(string[] args)
        {
            string pattern = @"^\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\s*$";
            string input = "H3Y5NC8E-TGA5B6SB-2NVAQ4E0";
            Regex re = new Regex(pattern);
            Match m = re.Match(input);
    
            if (m.Success)
                foreach (Capture c in m.Groups["group"].Captures)
                    Console.WriteLine(c.Value);
        }
    
    0 讨论(0)
  • 2021-01-14 09:25

    Why use Regex? If the groups are always split by a -, can't you use Split()?

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

    BTW, you can replace [ABCDEFGHJKLMNPQRSTVXYZ0123456789] character class with a more readable subtracted character class.

    [[A-Z\d]-[IOUW]]
    

    If you just want to match 3 groups like that, why don't you use this pattern 3 times in your regex and just use captured 1, 2, 3 subgroups to form the new string?

    ([[A-Z\d]-[IOUW]]){8}-([[A-Z\d]-[IOUW]]){8}-([[A-Z\d]-[IOUW]]){8}
    

    In PHP I would return (I don't know .NET)

    return "$1 $2 $3";
    
    0 讨论(0)
  • 2021-01-14 09:31

    Sorry if this isn't what you intended, but your string always has the hyphen separating the groups then instead of using regex couldn't you use the String.Split() method?

    Dim stringArray As Array = someString.Split("-")
    
    0 讨论(0)
提交回复
热议问题