Cover by Steven Levithan, Jan Goyvaerts

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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()) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required