2017-07-30 44 views
1

我从一个聊天客户端传来消息,我想解析一个#号,然后提取1-3位数字后加上数字后面的一个字母。由于我不知道这个数字是否是1,2或3位数字,我将每个数字都测试为一个整数,然后分配这些变量。我想出了下面的代码,但我的编程技巧是非常基本的...从JavaScript中的字符串中提取数据的更有效方法?

var test = 'it doesnt matter how long the message is I only need #222c'; 
var QuID = ''; 
var Qans = ''; 
var regInteger = /^\d+$/; 


//this function checks to see if a charactor is an integer 
function isInteger(str) {  
    return regInteger.test(str); 
} 

var IDloc = test.indexOf('#') + 1; 
var IDloc2 = test.indexOf('#') + 2 
console.log(IDloc); 

//This is a brute force method to test if there is a 1-3 digit number and assigning the question number and question answer into variables. Sloppy but it's duct tape and wire programming my friend! 
if(isInteger(test.substring(IDloc, IDloc2))) { 
    QuID = (test.substring(IDloc, IDloc2)); 
    Qans = (test.substring((IDloc + 1), (IDloc2 + 1))); 
    if (isInteger(test.substring((IDloc +1), (IDloc2 + 1)))) { 
     QuID = (test.substring(IDloc, (IDloc2 + 1))); 
     Qans = (test.substring((IDloc + 2), (IDloc2+ 3))); 
      if (isInteger(test.substring((IDloc + 2), (IDloc2 + 2)))) { 
       QuID = (test.substring(IDloc, (IDloc2 + 2))); 
       Qans = (test.substring((IDloc + 3), (IDloc2 + 4))); 
      } 
    } 

    console.log(QuID); 
    console.log(Qans); 
} else { 
    console.log('Non Integer'); 
} 

有没有,因为我觉得这是一个强力的方法来编写这更有效的方式。

+1

使用您的正则表达式使用组匹配提取值。 – Dai

回答

3
var result = test.match(/#(\d{1,3})([a-zA-Z])/); 
if (result) { 
    var numbers = result[1]; 
    var character = result[2]; 
} 

这提取1-3个数字(#号之后)之后的一个字符(在如果您需要任何特殊字符(例如,您需要添加的特殊字符),可以将它们分成两个不同的捕获组,然后将这些捕获组读入两个变量。请注意,这只会提取第一个匹配项。

+2

这工作完美,它使我的代码耻辱! – Palgrave

2

您可以搜索#并将数字后面的数字。

var getNumber = s => (s.match(/#(\d+)/) || [])[1]; 
 
    
 
console.log(getNumber('it doesnt matter how long the message is I only need #222c')); 
 
console.log(getNumber('foo')); 
 
console.log(getNumber('fo2o'));

0
var test = 'it doesnt matter how long the message is I only need #222c'; 
var result=0; 
(test.split("#")[1]||"").split("").every(char=>parseInt(char,10)&&(result=result*10+ +char)); 
console.log(result); 

只是一个非正则表达式的答案...