473,659 Members | 3,117 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need help with a Regular Expression

After much scouring of information on Regular Expressions from books and the
web, I've come up with the this handy little Regex to parse links from HTML:

<a\s+href(?:\s+ )?=(?:\s+)?[""']+(.?[^'""]+)['""]+(?:\s+)?>(.*?) </a>

It works quite well at extracting the url and title of a link from an anchor
tag, with one major problem--if the anchor tag includes other attributes
after the HREF= attribute, such as TITLE= or TARGET=, it doesn't consider it
a match. Here are some examples:

This one matches:
<a href="/">Home</a>
Group 1: "/"
Group 2: "Home"

This one doesn't:
<a href="/" target="_blank" >Home</a>

I can't figure out how to match just the href attribute and just the link
text. Any help would be appreciated.

Thanks.
Nov 20 '05 #1
2 1462
Hi,
Maybe this will help.
Dim wc As New System.Net.WebC lient

Dim sr As New System.IO.Strea mReader(wc.Open Read("http://news.google.com/"))

Dim strHtml As String

Dim regLink As New
System.Text.Reg ularExpressions .Regex("\""(?<u rl>[^\""]*)\""")

Dim regTitle As New System.Text.Reg ularExpressions .Regex(">(.*?)\ <")

Dim regHref As New System.Text.Reg ularExpressions .Regex("\<a
href=""(.*?)""\ >(.*?)\<\/a\>")

Dim m As System.Text.Reg ularExpressions .Match

strHtml = sr.ReadToEnd

Try

For Each m In regHref.Matches (strHtml)

Dim mLink As System.Text.Reg ularExpressions .Match

For Each mLink In regLink.Matches (m.ToString())

Trace.WriteLine (String.Format( "Link {0}", mLink.ToString) )

Next

For Each mLink In regTitle.Matche s(m.ToString())

Dim strTitle As String = mLink.ToString

strTitle = strTitle.Replac e(">", "")

strTitle = strTitle.Replac e("<", "")

Trace.WriteLine (String.Format( "Title {0}", strTitle))

Next

Next

Catch

End Try

sr.Close()

wc.Dispose()

Ken

----------------------------

"Luhar" <lu***@luharsof tworks.com> wrote in message
news:uH******** *****@TK2MSFTNG P10.phx.gbl...
After much scouring of information on Regular Expressions from books and the
web, I've come up with the this handy little Regex to parse links from HTML:

<a\s+href(?:\s+ )?=(?:\s+)?[""']+(.?[^'""]+)['""]+(?:\s+)?>(.*?) </a>

It works quite well at extracting the url and title of a link from an anchor
tag, with one major problem--if the anchor tag includes other attributes
after the HREF= attribute, such as TITLE= or TARGET=, it doesn't consider it
a match. Here are some examples:

This one matches:
<a href="/">Home</a>
Group 1: "/"
Group 2: "Home"

This one doesn't:
<a href="/" target="_blank" >Home</a>

I can't figure out how to match just the href attribute and just the link
text. Any help would be appreciated.

Thanks.

Nov 20 '05 #2
Thanks Ken. I'll try that.

While I was waiting for somebody to reply, I refined my original regex a bit
and it seems to find the url and text of href tags, no matter how the tag is
formatted. Here it is:
<\s*a\s*.*[^href]?href\s*={1}?[\s""']*([^\s'"">]*)[^>]*?>{1}(.*?\n*.* ?)</a>+
?
Looks ugly, but it seems to do the job. First capture group is the entire
tag from the opening <a... to the closing ...</a>. The second capture group
is just the url, including the protocol, host, destination, fragments, and
queries if they exist. The third capture group is the text between the <a>
and </> tags, including any embedded html tags.

If anybody can think of a situation where this regex doesn't match an anchor
tag in html code, please let me know.

Thanks again,

Luhar

"Ken Tucker [MVP]" <vb***@bellsout h.net> wrote in message
news:Oj******** ******@TK2MSFTN GP09.phx.gbl...
Hi,
Maybe this will help.
Dim wc As New System.Net.WebC lient

Dim sr As New System.IO.Strea mReader(wc.Open Read("http://news.google.com/"))
Dim strHtml As String

Dim regLink As New
System.Text.Reg ularExpressions .Regex("\""(?<u rl>[^\""]*)\""")

Dim regTitle As New System.Text.Reg ularExpressions .Regex(">(.*?)\ <")

Dim regHref As New System.Text.Reg ularExpressions .Regex("\<a
href=""(.*?)""\ >(.*?)\<\/a\>")

Dim m As System.Text.Reg ularExpressions .Match

strHtml = sr.ReadToEnd

Try

For Each m In regHref.Matches (strHtml)

Dim mLink As System.Text.Reg ularExpressions .Match

For Each mLink In regLink.Matches (m.ToString())

Trace.WriteLine (String.Format( "Link {0}", mLink.ToString) )

Next

For Each mLink In regTitle.Matche s(m.ToString())

Dim strTitle As String = mLink.ToString

strTitle = strTitle.Replac e(">", "")

strTitle = strTitle.Replac e("<", "")

Trace.WriteLine (String.Format( "Title {0}", strTitle))

Next

Next

Catch

End Try

sr.Close()

wc.Dispose()

Ken

----------------------------

"Luhar" <lu***@luharsof tworks.com> wrote in message
news:uH******** *****@TK2MSFTNG P10.phx.gbl...
After much scouring of information on Regular Expressions from books and the web, I've come up with the this handy little Regex to parse links from HTML:
<a\s+href(?:\s+ )?=(?:\s+)?[""']+(.?[^'""]+)['""]+(?:\s+)?>(.*?) </a>

It works quite well at extracting the url and title of a link from an anchor tag, with one major problem--if the anchor tag includes other attributes
after the HREF= attribute, such as TITLE= or TARGET=, it doesn't consider it a match. Here are some examples:

This one matches:
<a href="/">Home</a>
Group 1: "/"
Group 2: "Home"

This one doesn't:
<a href="/" target="_blank" >Home</a>

I can't figure out how to match just the href attribute and just the link
text. Any help would be appreciated.

Thanks.

Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4349
by: Danny | last post by:
I am trying to do a regular expression to search for a url so anything that has http:\\www.hellothere.com but may not have the http:\\ and may not have the www and may not have http:\\www and should work for upper and lower case I tried this:
2
1764
by: Mike Andrews | last post by:
Guys, I've got a regular expression that will just not work. I can't get it work properly and I would like to see if someone out there can tell me if I'm doing this wrong, or if there is a problem with the regex C library for linux. Here's my regular expression: +(a|input|select|option|textarea|form|frame|iframe|area|base|link|icon:*)\s*((|])*)]
4
3220
by: Neri | last post by:
Some document processing program I write has to deal with documents that have headers and footers that are unnecessary for the main processing part. Therefore, I'm using a regular expression to go over each document, find out if it contains a header and/or a footer and extract only the main content part. The headers and the footers have no specific format and I have to detect and remove them using a list of strings that may appear as...
3
2292
by: Joe | last post by:
Hi, I have been using a regular expression that I don’t uite understand to filter the valid email address. My regular expression is as follows: <asp:RegularExpressionValidator id="valValidEmail" runat="server" ControlToValidate="txtEmail" ValidationExpression="^(+)(\.+)*@(+)(\.+)*(\.{2,4})$"
18
3026
by: Q. John Chen | last post by:
I have Vidation Controls First One: Simple exluce certain special characters: say no a or b or c in the string: * Second One: I required date be entered in "MM/DD/YYYY" format: //+4 How ??
3
1340
by: Lucky | last post by:
hi guys, i'm practising regular expression. i've got one string and i want it to split in groups. i was trying to make one regular expression but i didn't successed. please help me guys. i'm using .NET 2.0's Regular expression class. here is the string.
17
2781
by: Mark | last post by:
I must create a routine that finds tokens in small, arbitrary VB code snippets. For example, it might have to find all occurrences of {Formula} I was thinking that using regular expressions might be a neat way to solve this, but I am new to them. Can anyone give me a hint here? The catch is, it must only find tokens that are not quoted and not commented; examples follow
6
2229
by: deepak_kamath_n | last post by:
Hello, I am relatively new to the world of regex and require some help in forming a regular expression to achieve the following: I have an input stream similar to: Slot: slot1 Description: this is a description Slot: slot2
14
2259
by: Chris | last post by:
I need a pattern that matches a string that has the same number of '(' as ')': findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = Can anybody help me out? Thanks for any help!
0
6181
by: altavim | last post by:
Usually when you make regular expression to extract text you are starting from simple expression. When you got to know target text, you are extending your expression. Subsequently very hard to ready long set of special symbols and impossible to improve such expression. We have to create ’smart’ regular expression. Instead of write one line expression we prepare multi line text from which we shall generate our long expression. Here is a simple...
1
8528
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1976
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.