locked
Regular Expression to extract String RRS feed

  • Question

  • Hi,
    I need to extract matching strings from string.

    I want to extract string matches in between [Serial Number Or SNO Or S.NO.]
    i.e. any of the above words might repeat any time any where in string. So I want to just extract the string after any of the above words matches till any of the word is found again, which can occur multiple times.
    I need regular expression for this but i am new to regular expression. I may end up writing some extra C# code i want to avoid.

    Example string:
    ......xyz.......

    ...........
    Serial Number Or SNO Or S.NO.
    ...................abcd........
    ...some...words....
    Serial Number Or SNO Or S.NO.
    ...more...words......

    Result:

    I should get:

    1.
    ...................abcd........
    ...some...words....

    2.
    ...more...words......

    Monday, August 1, 2016 8:55 AM

Answers

  • Try this sample:

    string example = @"
    ......xyz.......
    ...........
    S.NO.
    ...................abcd........
    ...some...words....
    Serial Number
    ...more...words......
    ";
    
    string pattern = @"(?:Serial Number|SNO|S[.]NO[.])(.*?)(?=Serial Number|SNO|S[.]NO[.]|$)";
    
    foreach( var m in Regex.Matches( example, pattern, RegexOptions.Singleline ).Cast<Match>() )
    {
        string serial_number = m.Groups[1].Value;
    
        Console.WriteLine( "FOUND: {0}", serial_number );
    }
    
    

    • Proposed as answer by Hart Wang Wednesday, August 3, 2016 8:55 AM
    • Marked as answer by DotNet Wang Wednesday, August 17, 2016 2:01 AM
    Monday, August 1, 2016 12:03 PM