happyZZR1400
happyZZR1400

Reputation: 2415

How to make regex to catch optional group

I want to find expression that will bring to me 2 or three groups into array, while the third group is optional (can be or not to be)
here is expression i use so far:

var expr = /^\s*(.+)\s+in\s+(.*?)\s*$/

if user only have 'thing in Things' - i want matches array to be as following:

[1] - thing

[2] - Things

if user have 'thing in Things | orderBy "id"' - i want matches array to be as following:

[1] - thing

[2] - Things

[3] - | orderBy "id"
console.log('2:'+'thing in Things'.match(expr)[2])  //-want it to be "Things" 
console.log('3:'+'thing in Things | orderBy "id"'.match(expr)[3])  //want it to be 'orderBy "id"''  (currently - undefined)

here is link to jsbin that demonstates problem:

Thanks forwards

Upvotes: 0

Views: 62

Answers (1)

Dean Taylor
Dean Taylor

Reputation: 42051

Something like this: /^\s*(.+)\s+in\s+(.*?)\s*(?:\s+\|\s+(.*))?$/

Regular expression visualization

Upvotes: 1

Related Questions