Regex negative lookahead.

W

writebrent

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</a> below

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

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
 
K

Kevin Spencer

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.
 
G

Greg Bacon

: 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</a> below
:
: [...]

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.RegularExpressions;

using MbUnit.Framework;

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

public string ExtractItem(string 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\">Item 6. Other</a> below", null)]
[Row("<abc>Item 7.</abc>",
"Item 7.")]
public void LookForInterestingItems(string input, string expect)
{
ItemScanner scanner = new ItemScanner();
Assert.AreEqual(expect, scanner.ExtractItem(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</em> bad!</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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top