user578895
user578895

Reputation:

optional regex lookahead

I'm trying to get an optional lookahead but am having problems where as soon as I make it optional (add a ? after it), it no longer matches even when the data is there.

As a brief summary, I'm trying to pull specific querystring params out of a URI. Example:

/.*foo.html\??(?=.*foo=([^\&]+))(?=.*bar=([^\&]+))/
    .exec( 'foo.html?foo=true&bar=baz' )

I'll break that out a bit:

.*foo.html\??      // filename == `foo.html` + '?'
(?=.*foo=([^\&]+)) // find "foo=...." parameter, store the value
(?=.*bar=([^\&]+)) // find "bar=...." parameter, store the value

The above example works perfectly under the condition that both foo and bar exist as parameters in the querystring. The issue is that I'm trying to make these optional, so I changed it to:

/.*foo.html\??(?=.*foo=([^\&]+))?(?=.*bar=([^\&]+))?/
                                ↑                  ↑
    Added these question marks ─┴──────────────────┘

and it no longer matches any parameters, though it still matches foo.html. Any ideas?

Upvotes: 9

Views: 1037

Answers (1)

Bergi
Bergi

Reputation: 664548

Try to put the question marks into the look-ahead:

...((?=(?:.*foo=([^\&]+))?)...

Looks odd, but I think a good-looking regex wasn't the aim :-)

Also, have you thought about this one?

/.*foo.html\??.*(?:foo|bar)=([^\&]+).*(?:bar|foo)=([^\&]+)/

Upvotes: 4

Related Questions