Search code examples
c#regular-language

C# need regular expression to capture the second occurence after a underscore


I am using the regular expression below to capture all numbers/letters after a underscore but I need to capture only the second occurence i.e "00500" as you see below:

regular expresion: (?<=_)[a-zA-Z0-9]+

string:
"-rw-rw-rw- 1 rats rats 31K Sep 17 13:33 /opt/data/automation_sent/20180918/labc/0/20180918_00500.itx"

I am doing in C# and I thought the value would be in the second group[1] but it is not; it only captures the string "_sent":

        string temp2 = "";
        Regex getValueAfterUnderscore = new Regex(@"(?<=_)[a-zA-Z0-9]+");
        Match match2 = getValueAfterUnderscore.Match(line);
        if (match2.Success)
        {
            temp2 = match2.Groups[1].Value;
            Console.WriteLine(temp2); 
        }

Any ideas? Thank you!


Solution

  • you can use the following code that capture text after second underscore

     var line = "-rw-rw-rw- 1 rats rats 31K Sep 17 13:33 /opt/data/automation_sent/20180918/labc/0/20180918_00500.itx";
                string temp2 = "";
                Regex getValueAfterUnderscore = new Regex(@"_.+_([a-zA-Z0-9]+)");
                Match match2 = getValueAfterUnderscore.Match(line);
                if (match2.Success)
                {
                    temp2 = match2.Groups[1].Value;
                    Console.WriteLine(temp2); 
                }
    

    output:

    00500