Lee Armstrong
Lee Armstrong

Reputation: 11450

How to convert regexp from lookahead

I have the following Regex in PHP and other code that is doing a great job.

/^(?:(?=[^ ]+\d)(?:[A-Z0-9]+))|(?:[A-Z0-9]+) +?(?=.*\d)(?:[A-Z0-9]+)?

Regular expression visualization

Debuggex Demo

It turns out that Go doesn't support lookheads and I'm at a loss on how to convert it across.

The Debuggex link has some test data I was using to qualify the code before.

Upvotes: 1

Views: 1648

Answers (1)

Bohemian
Bohemian

Reputation: 425238

Firstly, the left hand side of the alternation /^... matches nothing, because / can never appear before start of input.

That leaves just (?:[A-Z0-9]+) +?(?=.*\d), which can be expressed as:

((?:[A-Z0-9]+) ).*\d.*

The term " +?" as used is identical in effect to just " ".

Note however that this consumes more input than the original, which is unavoidable. Your original match is now in group 1.

Upvotes: 1

Related Questions