CJ Scholten
CJ Scholten

Reputation: 713

regex get text from next line

I'm looking for a way to find text on the next line of a certain string using regex.
Say I have the following text:

Note:
Just some text on this line

Some more text here.

I just want to get the text 'Just some text on this line'.
I don't know exactly what the other text will be, so I can't search between 'Note:' and 'Some more text here'.
All I know is that the text I want is on the next line from 'Note:'.
How could I do this?

Cheers, CJ

Upvotes: 0

Views: 3585

Answers (3)

Anirudha
Anirudha

Reputation: 32807

You can do this

(?<=Note:(\r?\n)).*?(?=(\r?\n)|$)
---------------- --- ------------
      |           |        |->lookahead for \r\n or end of string
      |           |->Gotcha
      |->lookbehind for note followed by \r\n. \r is optional in some cases

So,it would be like this

string nextLine=Regex.Match(input,regex,RegexOptions.Singline | RegexOptions.IgnoreCase ).Value;

Upvotes: 0

I'd go line by line down your string, and when a regex matches, then take the next line

string str;
// if you're not reading from a file, String.Split('\n'), can help you
using (StreamReader sr = new StreamReader("doc.txt"))
{
    while ((str = sr.ReadLine()) != null)
    {
        if (str.Trim() == "Note:") // you may also use a regex here if applicable
        {
            str = sr.ReadLine();
            break;
        }
    }
}

Console.WriteLine(str);

Upvotes: 2

MattW
MattW

Reputation: 4628

This can be done with a multiline regex, but are you sure you want to? It sounds more like a case for line-by-line processing.

The Regex would be something like:

new Regex(@"Note:$^(?<capture>.*)$", RegexOptions.MultiLine);

although you might need to make that first $ a \r?$ or a \s*$ because $ only matches \n not the \r in \r\n.

Your "Just some text on this line" would be in the group named capture. You might also need to strip a trailing \r from this because of the treatment of $.

Upvotes: 1

Related Questions