Ragen Dazs
Ragen Dazs

Reputation: 2170

Regex match negative optional group

I'm trying to match MenuSearch and User in this ocurrencies:

/MenuSearch?action=read
/User

The following regex match the first case:

/\/(.*)(?=\?)/g

But doesn't match User because they doesn't have ? character in your line. How can I can make the second regex group optional?

See online: https://regex101.com/r/qU6hN6/2

Upvotes: 1

Views: 93

Answers (3)

paulgoblin
paulgoblin

Reputation: 157

/\/([^?^\n]*)(\?.*)?/g

This grabs a forward slash, \/ , followed by any number of non-? non-newline characters, ([^?^\n]*), optionally followed by a question mark followed by any number of characters, (\?.*)?

The first capture group is the menu item, the second capture group is the query.

Upvotes: 1

nbsp
nbsp

Reputation: 340

You could also use the \w metacharacter if you just need to find word characters.

\/(\w+)/g

Upvotes: 0

anubhava
anubhava

Reputation: 786289

You can use this negation based regex:

/^\/([^?]+)/gm

Updated RegEx Demo

Upvotes: 0

Related Questions