regex – Java pattern matcher – optional capturing group

I’d like to process some input queries in 3 possible ways:

query: select * from People 
query: select * from People exclude addresses
query: select * from People include department

I have a regex query[:\/]?(.*)((exclude|include)(.*))? that MATCHES all three scenarios, but I lose the groups (2) like: exclude addresses, include departments, but I’ll have to use extra substring operations to extract this info from the original string.

With query[:\/]?(.*)((exclude|include)(.*)) (no question mark at the end)

I get:

  • group 1 – Query ONLY
  • group 2 (exclusions/inclusions)

But it doesn’t capture cases when I get only the query input.

How to update the RegEx that I have MATCH on all 3 cases with optional matching groups? i.e. groupCount == 3, I have inclusions/exclusions, and groupCount == 2 indicates I have a simple query only. Thank you.

Read more here: Source link