473,802 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regex negative lookahead.

I think I need to do a negative lookahead with a regular expression,
but I'm a bit confused how to make it all work. Take these example
texts:

Need to match these two:
=============== ==========

Item 4.01 Regulation and other items
<b>Item 4. Regulation</b>

=============== ==========
Need to avoid matching these two:
=============== ==========

....then he looked at Item 12.06 for more information...
<a href="000">Item 6. Other</abelow

=============== ==========

In other words, I need to match a string as follows:

0. Begining of line or ">"
1. The word "Item",
2. Single space,
3. A number containing at least one or more digits and a period,
4. Some more text,
5. Terminating either in an end of line, or "<"
6. Except, not terminating in "</a" (i.e., exclude hyperlinks).

My proposed (nonworking) solution is this:

(?:^|>)(?<item> Item\s\d+\..*?) (?!</a>)(?:<|$)

The problem is that it still matches all hyperlinks.

I'd sure appreciate any help you might have.

Thanks.

--Brent

Oct 7 '06 #1
2 7265
Remember that a negative and a positive are opposites, and the negative of a
negative is a positive (and vice versa). Here's the regular expression you
need (depending on your rules, you may want to tweak it slightly, but AFAIK
it satisfies all of your requirements (I didn't know whether or not you
wanted to include the brackets):

(?i)(?:<[b-z]*>)?Item\s+\d+\ .\d*\s+\w*(?:</[b-z]+>)?

It is case-insensitive ("(?i)"). and matches your rules, using a range of
characters from b to z, on both ends. I didn't assume only one space, but
one or more. Again, you may want to tweak it, but if there's one space, it
works fine.

--
HTH,

Kevin Spencer
Microsoft MVP
Computer Control Freak
http://unclechutney.blogspot.com

A man, a plan, a canal, a palindrome that has.. oh, never mind.

<wr********@gma il.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
>I think I need to do a negative lookahead with a regular expression,
but I'm a bit confused how to make it all work. Take these example
texts:

Need to match these two:
=============== ==========

Item 4.01 Regulation and other items
<b>Item 4. Regulation</b>

=============== ==========
Need to avoid matching these two:
=============== ==========

...then he looked at Item 12.06 for more information...
<a href="000">Item 6. Other</abelow

=============== ==========

In other words, I need to match a string as follows:

0. Begining of line or ">"
1. The word "Item",
2. Single space,
3. A number containing at least one or more digits and a period,
4. Some more text,
5. Terminating either in an end of line, or "<"
6. Except, not terminating in "</a" (i.e., exclude hyperlinks).

My proposed (nonworking) solution is this:

(?:^|>)(?<item> Item\s\d+\..*?) (?!</a>)(?:<|$)

The problem is that it still matches all hyperlinks.

I'd sure appreciate any help you might have.

Thanks.

--Brent

Oct 7 '06 #2
In article <11************ **********@m73g 2000cwd.googleg roups.com>,
<wr********@gma il.comwrote:

: I think I need to do a negative lookahead with a regular expression,
: but I'm a bit confused how to make it all work. Take these example
: texts:
:
: Need to match these two:
: =============== ==========
:
: Item 4.01 Regulation and other items
: <b>Item 4. Regulation</b>
:
: =============== ==========
: Need to avoid matching these two:
: =============== ==========
:
: ...then he looked at Item 12.06 for more information...
: <a href="000">Item 6. Other</abelow
:
: [...]

When you're having trouble getting the right pattern, turn the
verbosity knob way up. In other words, be explicit about the
different cases:

using System;
using System.Text.Reg ularExpressions ;

using MbUnit.Framewor k;

namespace Item
{
public class ItemScanner
{
static Regex valid =
new Regex(@"
^(?<item>Item\s \d+\.\d*.+) |
>(?<item>Item\s \d+\.\d*.*?)<(? !/a>)",
RegexOptions.Ig norePatternWhit espace);

public string ExtractItem(str ing s)
{
Match m = valid.Match(s);
return m.Success ? m.Groups["item"].Value : null;
}
}

[TestFixture]
public class Test
{
[RowTest]
[Row("Item 4.01 Regulation and other items",
"Item 4.01 Regulation and other items")]
[Row("<b>Item 4. Regulation</b>",
"Item 4. Regulation")]
[Row("...then he looked at Item 12.06 for more...", null)]
[Row("<a href=\"000\">It em 6. Other</abelow", null)]
[Row("<abc>Item 7.</abc>",
"Item 7.")]
public void LookForInterest ingItems(string input, string expect)
{
ItemScanner scanner = new ItemScanner();
Assert.AreEqual (expect, scanner.Extract Item(input));
}
}
}

Using negative lookahead is tricky because it's easy to forget that
the matcher is the Little Engine That Could: the pesky thing will
keep on backtracking until it finds a match.

Consider a paraphrased version of your pattern:

Item\s\d+\..*?( ?!</a>)

For "Item 7. blah</a>", the matcher sees the dot after one or more
digits and then tries the negative lookahead without consuming any
more input, i.e., .*? tries first tries zero repititions, then one,
then two, and so on. The string " blah</a>" does not start with
"</a>", so the match succeeds.

In general, the more anchors or checkpoints you can put in your
patterns, the easier you'll make it on yourself. Note that in my
pattern, I match a less-than that I'm going to throw away. Because I'm
in the string-value branch, I know I have to find a less-than, so I
look for it and then make sure it's not a bad end element.

PLEASE NOTE: All that said, regular expressions are *very* poor
substitutes for HTML parsers. Say you have the following item:

<b>Item 4. <em>Really</embad!</b>

My pattern will report "Item 4. " as the item, which is probably
not what you want.

Find another approach if possible, e.g., XPath if your documents are
XHTML.

Hope this helps,
Greg
--
Those who are asking for more government interference are asking
ultimately for more compulsion and less freedom.
-- Ludwig von Mises
Oct 9 '06 #3

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

Similar topics

2
2378
by: brendan | last post by:
Hi ... want to antispam any email address that is written in a page, so long as it is not already contained in a hyperlink ie 'mailto:user@email.com' so am trying to use a negative look behind but I can't get it to work preg_replace('/(?<!mailto)((+)@(+))/i', "<script>document.write('<a href=\'mailto:'+'\\1'+'@'+'\\2'+'\'>'+'\\1'+'@'+'\\2'+'</a>');</script>",$st ring );
2
2001
by: John Baro | last post by:
I need to determine when multiple fonts are selected in a richtextbox. A font is indicated by \fcharset(N) where (N) is a number. (To the best of my knowledge) I can use this statement int Matches = 0; for(Match m = Regex.Match(rtfTextEdit.SelectedRtf, @"\\fcharset\d"); m.Success; m = m.NextMatch()) {
2
6846
by: D | last post by:
My first attempt at this and I'm searching formulas like so RIGHT(TEXT(A15,'yy'),1)*1000+A15-CONCATENATE(1,'-','jan','-',TEXT(A15,'yy'))+1 I want to extract the row / col coordinates (A15 in above) so I'm using this +\d+\d* however I want unique ones and not 3 copies of A15 as the above returns.
3
1822
by: pagates | last post by:
Hi All, It might be because its the end of a long week, but I can't figure out the correct way to write a regular expression to find all matches except a specified string. For example, take the following 3 lines: This is OK This is Not OK Again This is OK
13
2379
by: Chris Lieb | last post by:
I am trying to write a regex that will parse BBcode into HTML using JavaScript. Everything was going smoothly using the string class replace() operator with regex's until I got to the list tag. Implementing the list tag itself was fairly easy. What was not was trying to handle the list items. For some reason, in BBcode, they didn't bother defining an end tag for a list item. I guess that they designed it with bad old HTML 3.2 in mind...
1
1872
by: Prabhu Gurumurthy | last post by:
Hello all - I have a file which has IP address and subnet number and I use regex to extract the IP separately from subnet. pattern used for IP: \d{1,3}(\.\d{1,3}){3} pattern used for subnet:((\d{1,3})|(\d{1,3}(\.\d{1,3}){1,3}))/(\d{1,2}) so I have list of ip/subnets strewn around like this
7
3151
by: intrader | last post by:
The regular expression is /(?!((00000)|(11111)))/ in oRe. That is oRE=/(?!((00000)|(11111)))/ The test strings are 92708, 00000, 11111 in checkStr The expression used is checkStr.search(oRE). The values returned are are 0,1,1 - the values should be 0,-1,-1. The positive lookahead expressiono RE=/(?=((00000)|(11111)))/ returns -1, 0, 0 respectively - this is correct
4
1256
by: Johny | last post by:
I have string="""<span class="test456">55</span>. <td><span class="test123">128</span> <span class="test789">170</span> """ where I need to replace <span class="test456">55</span>. <span class="test789">170</span>
5
2317
by: vbgunz | last post by:
/* * BEGIN EXAMPLES */ var text = 'A Cats Catalog of Cat Catastrophes and Calamities'; /*** * EXAMPLE 1: negative lookahead assertion logic ***/
0
9562
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10536
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10304
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6838
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
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
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
3792
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2966
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.