2013-03-03 74 views
1

我有這樣的正則表達式表達對Java環境如預期的工作,但我unabled使它JavaScript的正常工作:的Javascript正則表達式缺少組

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

這種表達應該符合這些類型的輸入線:

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 

而對於組我期望:

1:第一投影別名(a)如任何

2:第一投影屬性(ID),如果任何

3:第二突起別名(a)如任何

4:第二突起屬性(名稱)如果任何

5:關係名(公共.blah)

6:關係別名(a)如果任何

正則表達式是匹配於JavaScript,但它只是無法獲取組。必須有一些我需要改變這一點,使其工作。

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 
} 

你們有什麼需要改變的線索嗎?

謝謝!

回答

2

刪除g標誌。它正在將您的正則表達式從「匹配並返回子模式」更改爲「搜索並返回所有匹配項」

+0

Works!我失明瞭!謝謝。 – 2013-03-03 21:01:15

+0

無論如何,我不得不做一個小的改變,因爲屬性的第一個字母被認爲是別名,所以最後是:
/^(?: select \ s +)?(?:(?:([\ w \ d] +)\)([\ W \ d] +))(:???\ S * \,\ S *)(?:?(?:([\ W \ d] +)\。 )([\ W \ d] +))(:????\ S *從\ S +)([。\ W \ d \] +)\ S *([\ W \ d] +)$ / – 2013-03-03 21:01:47