Skip to Content
Regular Expressions Cookbook
book

Regular Expressions Cookbook

by Jan Goyvaerts, Steven Levithan
May 2009
Intermediate to advanced
510 pages
15h
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook

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()) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Regular Expressions Cookbook, 2nd Edition

Regular Expressions Cookbook, 2nd Edition

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9780596802837Catalog PageErrata