3.21. Search Line by Line

Problem

Traditional grep tools apply your regular expression to one line of text at a time, and display the lines matched (or not matched) by the regular expression. You have an array of strings, or a multiline string, that you want to process in this way.

Solution

C#

If you have a multiline string, split it into an array of strings first, with each string in the array holding one line of text:

string[] lines = Regex.Split(subjectString, "\r?\n");

Then, iterate over the lines array:

Regex regexObj = new Regex("regex pattern");
for (int i = 0; i < lines.Length; i++) {
    if (regexObj.IsMatch(lines[i])) {
        // The regex matches lines[i]
    } else {
        // The regex does not match lines[i]
    }
}

VB.NET

If you have a multiline string, split it into an array of strings first, with each string in the array holding one line of text:

Dim Lines = Regex.Split(SubjectString, "\r?\n")

Then, iterate over the lines array:

Dim RegexObj As New Regex("regex pattern")
For i As Integer = 0 To Lines.Length - 1
    If RegexObj.IsMatch(Lines(i)) Then
        'The regex matches Lines(i)
    Else
        'The regex does not match Lines(i)
    End If
Next

Java

If you have a multiline string, split it into an array of strings first, with each string in the array holding one line of text:

String[] lines = subjectString.split("\r?\n");

Then, iterate over the lines array:

Pattern regex = Pattern.compile("regex pattern"); Matcher regexMatcher = regex.matcher(""); for (int i = 0; i < lines.length; i++) { regexMatcher.reset(lines[i]); if (regexMatcher.find()) ...

Get Regular Expressions Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.