Negative Lookbehind and Wildcards

  • Thread starter Thomas F. O'Connell
  • Start date
T

Thomas F. O'Connell

I've been looking through the negative lookbehind posts and haven't
yet found a definitive answer to the question I'm about to ask:

Does negative lookbehind have lower precedence than even a non-greedy
wildcard (*) in the Perl regular expression engine?

The reason I ask is the following scenario:

I am try to match a pattern B as long as it is not preceded by a
pattern A in a given string, regardless of what occurs between B and
A.

To me, this seems a natural use of negative lookbehind. But when I try
the following expression:

/(?!<A).*B/

it does not work as I expect it to. I've tried both greedy and
non-greedy wildcards, and the only thing I can think is that the
wildcard takes precedence in matching up to B because of the rules of
matching in the engine. Is that correct?

Is there a way to solve this problem?

I've got Perl 5.8.0 for Linux.

Thanks!

-tfo
 
G

Gunnar Hjalmarsson

Thomas said:
I am try to match a pattern B as long as it is not preceded by a
pattern A in a given string, regardless of what occurs between B
and A.

To me, this seems a natural use of negative lookbehind. But when I
try the following expression:

/(?!<A).*B/

Suppose you mean

/(?<!A).*B/

But that does not help, since .* matches anything, including pattern
A, from the beginning of the string.
it does not work as I expect it to. I've tried both greedy and
non-greedy wildcards, and the only thing I can think is that the
wildcard takes precedence in matching up to B because of the rules
of matching in the engine. Is that correct?

I don't think it is about precedence. The problem is that a dot
matches any character.
Is there a way to solve this problem?

One way might be to replace the dot with a character class that does
not include one or more characters that are included in pattern A.

If you know that pattern B can only occur once, I suppose it's easiest
to simply use two regexes:

/B/ and !/A.*B/

HTH
 

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

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top