2011-09-02 109 views
1

我正在研究解析文本字段的函數。以下是一些情況:Javascript正則表達式匹配

In: "about" 
Result: var keywords = "about" 

In: "type:page " (notice the space) 
Result: var types = ["page"]; 

In: "type:page about" 
Result: var types = ["page"], keywords = "about"; 

In: "type:page,event The Event" 
Result: var types = ["page", "event"], keywords = "The Event"; 

有人可以指出我正確的方向,我將如何使用RegEx解析此問題嗎?

+0

'事件類型:頁面,事件'怎麼樣?我認爲你需要寫一個完整的函數,而不是一行正則表達式 – timdream

回答

1
 function inOut (input) { 
     var output = {}; 
     if (input.indexOf('type:') !== -1) { 
      output.types = input.replace(/^.*type:([^ ]+).*$/, '$1').split(','); 
      output.keywords = input.replace(/^(.*)type:([^ ]+)(.*)$/, '$1 $3'); 
     } else { 
      output.keywords = input; 
     } 
     return output; 
    } 

試試這個嗎?

+0

很好,謝謝! – Matt