Extract comma separated portion of string with a RegEx in C#

后端 未结 4 1362
失恋的感觉
失恋的感觉 2021-01-22 17:22

Sample data: !!Part|123456,ABCDEF,ABC132!!

The comma delimited list can be any number of any combination of alphas and numbers

I want a regex to match the entri

相关标签:
4条回答
  • 2021-01-22 18:02

    I think the RegEx you are looking for is this:

    (?:^!!PART\|){0,1}(?<value>.*?)(?:,|!!$)
    

    This can then be run like this

            string tag = "!!Part|123456,ABCDEF,ABC132!!";
    
            string partRegularExpression = @"(?:^!!PART\|){0,1}(?<value>.*?)(?:,|!!$)";
            ArrayList results = new ArrayList();
    
            Regex extractNumber = new Regex(partRegularExpression, RegexOptions.IgnoreCase);
            MatchCollection matches = extractNumber.Matches(tag);
            foreach (Match match in matches)
            {
                results.Add(match.Groups["value"].Value);
            }            
    
            foreach (string s in results)
            {
                Console.WriteLine(s);
            }
    
    0 讨论(0)
  • 2021-01-22 18:05

    Unless I'm mistaken, that still only counts as one group. I'm guessing you'll need to do a string.Split(',') to do what you want? Indeed, it looks a lot simpler to not bother with regex at all here... Depending on the data, how about:

            if (tag.StartsWith("!!Part|") && tag.EndsWith("!!"))
            {
                tag = tag.Substring(7, tag.Length - 9);
                string[] data = tag.Split(',');
            }
    
    0 讨论(0)
  • 2021-01-22 18:20

    The following code

    string testString = "!!Part|123456,ABCDEF,ABC132!!";
    foreach(string component in testString.Split("|!,".ToCharArray(),StringSplitOptions.RemoveEmptyEntries) )
    {
        Console.WriteLine(component);
    }
    

    will give the following output

    Part
    123456
    ABCDEF
    ABC132
    

    This has the advantage of making the comma separated part of the string match up with the index numbers you (possibly accidentally incorrectly) specified in the original question (1,2,3).

    HTH

    -EDIT- forgot to mention, this may have drawbacks if the format of each string is not as expected above, but then again it would break just as easily without stupendously complex regex too.

    0 讨论(0)
  • 2021-01-22 18:24

    You can either use split:

    string csv = tag.Substring(7, tag.Length - 9);
    string[] values = csv.Split(new char[] { ',' });
    

    Or a regex:

    Regex csvRegex = new Regex(@"!!Part\|(?:(?<value>\w+),?)+!!");
    List<string> valuesRegex = new List<string>();
    foreach (Capture capture in csvRegex.Match(tag).Groups["value"].Captures)
    {
        valuesRegex.Add(capture.Value);
    }
    
    0 讨论(0)
提交回复
热议问题