473,387 Members | 1,742 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 7236
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********@gmail.comwrote in message
news:11**********************@m73g2000cwd.googlegr oups.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**********************@m73g2000cwd.googlegroups .com>,
<wr********@gmail.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.RegularExpressions;

using MbUnit.Framework;

namespace Item
{
public class ItemScanner
{
static Regex valid =
new Regex(@"
^(?<item>Item\s\d+\.\d*.+) |
>(?<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</abelow", 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</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
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...
2
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...
2
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...
3
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...
13
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....
1
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...
7
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...
4
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...
5
by: vbgunz | last post by:
/* * BEGIN EXAMPLES */ var text = 'A Cats Catalog of Cat Catastrophes and Calamities'; /*** * EXAMPLE 1: negative lookahead assertion logic ***/
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
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...

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.