John Jackson
John Jackson

Reputation: 73

JavaScript RegExp Optional Capture Group

Given these two strings:

let query = "select color, year from car where color = blue and year = 2002";

or

let query = "select color, year from car";

I created the following RegExp with String.prototype.match to extract the columns, the table name and the where clause (optional)

var results = query.match(/select (.*) from (.*) where (.*)/);

For the first query, the result is what I was expecting:

[ 
  'select color, year from car where color = blue and year = 2002',
  'color, year',
  'car',
  'color = blue and year = 2002',
  index: 0,
  input: 'select color, year from car where color = blue and year = 2002' 
]

For the second query, I got a null, and if I try to change the RegExp to consider the where clause optional, it changes the capture groups and also does not work:

var results = query.match(/select (.*) from (.*)( where (.*))?/);

Any idea about how to use capture groups, where one of those are optional, in this situation? I have other strategies to implement that but I really would like to keep using the capture groups.

Thanks

Upvotes: 7

Views: 6412

Answers (1)

Jared Smith
Jared Smith

Reputation: 22030

The answer is to surround the optional WHERE clause with a non-capturing group and make that optional. I've also change it slightly because you probably don't want to match any character .. You can always change that back.

var regex = /select\s+([\w ,]+)\s+from\s+(\w+)(?:\s+where([\w =]+))?/gi;

DEMO

I would be remiss though if I didn't mention that processing code with regexes is a terrible idea. You can always use an SQL parser.

Upvotes: 5

Related Questions