2015-10-21 155 views
2

分解字符串时出现问题。使用正则表达式分解带括号的字符串

问题:

我想分解的字符串是这样的:

(01)123456789(11)060606(17)121212(21)1321asdfght(10)aaabbb

,并返回一个像这样的对象:

Object { 
     identifier01: "123456789", 
     identifier11: "060606", 
     identifier17: "121212", 
     identifier21: "1321asdfght", 
     identifier10: "aaabbb" 
} 

规则:
identifier01有总是14个数字字符
identifier11始终6个数字字符
identifier17始终6个数字字符
identifier21始终为1至20个字母数字字符
identifier10始终为1至20个字母数字字符

的问题是identifier21和identifier10没有固定的字符长度(从1到20个字符不等)。更重要的是,只有identifier01总是在开头的标识符和其余的可以有不同的顺序,让我们说:

(01)123456789(21)111122233344(10)abcdeed(11)050505(17)060606

,甚至是特定的标识符可以根本不存在:

(01)123456789(21)111122233344(17)060606

我的方法:

parseStringToAnObject: function (value) { 
      var regs = [ 
       ["(01) ", /\([^)]*01\)([0-9]{14})/], 
       ["(10) ", /\([^)]*10\)([0-9a-zA-Z]{1,20})/], 
       ["(11) ", /\([^)]*11\)([0-9]{6})/], 
       ["(17) ", /\([^)]*17\)([0-9]{6})/], 
       ["(21) ", /\([^)]*21\)([0-9a-zA-Z]{1,20})/] 
      ]; 

      var tempObj = {}; 

      while (value.length > 0) { 
       var ok = false; 
       for (var i = 0; i < regs.length; i++) { 
        var match = value.match(regs[i][1]); 
        console.log(match); 
        if (match) { 
         ok = true; 
         switch (match[0].slice(0, 4)) { 
          case "(01)": 
           tempObj.identifier01 = match[1]; 
           break; 
          case "(21)": 
           tempObj.identifier21 = match[1]; 
           break; 
          case "(11)": 
           tempObj.identifier11 = match[1]; 
           break; 
          case "(17)": 
           tempObj.identifier17 = match[1]; 
           break; 
          case "(10)": 
           tempObj.identifier10 = match[1]; 
           break; 
         } 

         value = value.slice(match[0].length); 
         break; 
        } else { 
         console.log("Regex error"); 
        } 
       } 
       if (!ok) { 
        return false; 
       } 
      } 
      console.log(tempObj); 
      return tempObj; 
} 

结果:

我的函数返回一个适当的数据,但只有当我不键入可变数量的字符的标识符。当我输入例如

(01)123456789(21)abder123(17)121212

(01)123456789(10)123aaaaabbbddd(21)qwerty

(01)123456789(17)060606(10)aabbcc121212(11)030303

它总是返回我

您能否提出一个更好更精细的方法?
感谢您提前给出所有答案和解决方案!

回答

1

以下是我会做:

var s = "(01)123456789(11)060606(17)121212(21)1321asdfght(10)aaabbb", 
 
    r = {}; 
 

 
s.replace(/\((\d\d)\)([^()]+)/g, function(m,p,d){ r['identifier'+p]=d;return '';}); 
 
    
 
console.log(r);

1

我甚至不会使用正则表达式:

var final = {}; 
var a = "(01)123456789(11)060606(17)121212(21)1321asdfght(10)aaabbb"; 
a.split("(").slice(1).sort().map(function(i) { 
    var pieces = i.split(')'); 
    final["identifier" + pieces[0]] = pieces[1]; 
}); 
console.log(final); 

//Object {identifier01: "123456789", identifier10: "aaabbb", identifier11: "060606", identifier17: "121212", identifier21: "1321asdfght"} 
相关问题