2011-09-02 108 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