2013-12-12 109 views
0

我想找到將帶給我2或3個組的表達式,而第三組是可選的(可以或不可以)
這裏是我使用的表達式遠:如何使正則表達式捕獲可選組

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

如果用戶只具有「物聯網的東西」 - 我想匹配陣列是如下:

[1] - thing 

[2] - Things 

如果用戶擁有「的東西在物聯網|排序依據 「身份證」」 - 我想匹配陣列是如下:

[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) 

這裏是鏈接到jsbin該發現證明問題:

感謝前鋒

+1

你的意思是你想用'in'和'|'來分割字符串嗎? – Passerby

回答

1

事情是這樣的: /^\s*(.+)\s+in\s+(.*?)\s*(?:\s+\|\s+(.*))?$/

Regular expression visualization

+0

謝謝,你太棒了! – happyZZR1400