suchanoob
suchanoob

Reputation: 300

VB.NET: Get strings from lines between words

I am trying to find a way to grab the strings that are included between two words but I cannot figure out how to do it. I need each line to be added to a listbox.

For example:

First:
http://google.com
http://yahoo.com
default

Second:
http://facebook.com
http://123.com
http://test.com
default

Using this as an example, the first listbox needs to include the following items:

http://google.com
http://yahoo.com
default

And the second listbox should include those items:

http://facebook.com
http://123.com
http://test.com
default

How is this possible? I only know how to get a string between two words using split but it doesn't work in this case. Thanks in advance.

Upvotes: 0

Views: 110

Answers (3)

hwnd
hwnd

Reputation: 70722

Based off your data, you may consider using a Negative Lookahead to match the lines you want only.

For Each m As Match In Regex.Matches(input, "(?m)^(?!(?:First|Second):).+$")
    ListBox1.Items.Add(m.Value)

Upvotes: 1

Dalorzo
Dalorzo

Reputation: 20014

How about something like this:

(?<=First:)(.*)

Online RegEx Demo

With this code:

Dim options = RegexOptions.Singleline
Dim sampleInput="First:" + Environment.NewLine  + "http://google.com" + Environment.NewLine  + "http://yahoo.com" + Environment.NewLine  + "default"
Dim results = Regex.Match(sampleInput,"(?<=First:)(.*)",options).Value

Code Demo

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

I think you want something like this,

(?<=\n|^)First:(?:(?!\n\n).)*?(http://google\.com)(?:(?!\n\n|$).)*?(http://yahoo\.com)(?:(?!\n\n).)*?default(?=\n\n)|(?<=\n|^)Second:(?:(?!\n\n).)*?(http://facebook\.com)(?:(?!\n\n).)*?(http://123\.com)(?:(?!\n\n).)*?(http://test\.com)(?:(?!\n\n).)*?default(?=\n\n|$)

DEMO

Upvotes: 1

Related Questions