Luciano Greiner
Luciano Greiner

Reputation: 183

Javascript Regex Missing Groups

I have this regex expression working as expected on Java environment, but i am unabled to make it work properly on Javascript:

/^(?:select\s+)?(?:([\w\d]+)?\.?([\w\d]+))?(?:\s*\,\s*)?(?:([\w\d]+)?\.?([\w\d]+))?(?:\s*from\s+)([\w\d\.]+)\s*([\w\d]+)?$/g

This expression should match these kind of input lines:

select a.id, a.name from public.blah a

select a, a.name from public.blah a

select id, name from blah

a.id, name from brah a

from blah a

And for the groups I expect:

1: first projection alias (a) if any

2: first projection attribute (id) if any

3: second projection alias (a) if any

4: second projection attribute (name) if any

5: relation name (public.blah)

6: relation alias (a) if any

The regex is matching on Javascript, but it just can't fetch the groups. There must be something i need to change on this to make it work.

var optionsPattern = /^(?:select\s+)?(?:([\w\d]+)?\.?([\w\d]+))?(?:\s*\,\s*)?(?:([\w\d]+)?\.?([\w\d]+))?(?:\s*from\s+)([\w\d\.]+)\s*([\w\d]+)?$/g;

var text = 'select id, text from options.test';

var match = text.match(optionsPattern);

if(match) {
  alert(match[0]); // select id, text from options.test
  alert(match[1]); // undefined 
}

Do you guys have a clue of what needs to be changed on this?

Thank you!

Upvotes: 1

Views: 497

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Remove the g flag. It is changing your regex from "match and return subpatterns" to "search and return all matches"

Upvotes: 2

Related Questions