2017-09-20 77 views
1

重寫了這個問題,因爲命名捕獲組不是主要問題。Javascript正則表達式無效組

我有following regex now

/([a-zA-Z ]*)([0-9]*)/g 

代碼是現在的工作很好,但var m = /([a-zA-Z ]*)([0-9]*)/g.exec('Ashok : 9830011245')只給我阿肖克作爲結果。

m[0]: "Ashok" 
m[1]: "Ashok" 
m[2]: "" 

樣品字符串我需要工作它:

var strings = [ 
"Ashok : 9812340245", 
"Amit Singh :\nChakmir 9013123427\n\nHitendra Singh:\n\nM. : 9612348943", 
"ANIL AGARWAL : \n09331234728\n09812340442\nMAYANK AGARWAL : \n09123416042", 
"JAGDISH SINGH :  098123452187 \n09830111234", 
"MD QYAMUDDIN : 09433186333,\n09477215123\nMD TAJUDDIN : \n09831429111\nGYASUDDIN ANSARI :\n08961383686 \nMD BABUDDIN : \n09433336456 \n09903568555\nJAWE", 
"Viay Singh : 9330938789,\nBijay Singh : 9330938222", 
"Nilu :   09830161000,\n09331863222,\n09830071333,\nSantosh Upadhayay :  09831379555,\n09331727858,\n09830593322" 
]; 

請指導。

+0

JS正則表達式引擎不支持命名捕獲組。 –

+0

*'不支持命名捕獲組* *:但是:p https://github.com/tc39/proposal-regexp-named-groups –

+0

@WiktorStribiżew我已經刪除了名字,但現在我的exec函數沒有返回數字組價值。刪除我的命名組後,新的正則表達式是:/([a-zA-Z] *)([0-9] *)/ g。 –

回答

1

看來你可以提取你需要的所有子與

/^([^:0-9\n]+)\s*(?::\s*)?([0-9]*)/gm 

regex demo

詳細

  • ^ - 所述的開始(如m使多行模式)
  • ([^:0-9\n]+) - 1以上字符比:,數字和換行符
  • \s*其他 - 1個或多個空格
  • (?::\s*)? - 選項:和0+空格的序列
  • ([0-9]*) - 零個或多個數字。

JS演示:

var strings = [ 
 
"Ashok : 9812340245", 
 
"Amit Singh :\nChakmir 9013123427\n\nHitendra Singh:\n\nM. : 9612348943", 
 
"ANIL AGARWAL : \n09331234728\n09812340442\nMAYANK AGARWAL : \n09123416042", 
 
"JAGDISH SINGH :  098123452187 \n09830111234", 
 
"MD QYAMUDDIN : 09433186333,\n09477215123\nMD TAJUDDIN : \n09831429111\nGYASUDDIN ANSARI :\n08961383686 \nMD BABUDDIN : \n09433336456 \n09903568555\nJAWE", 
 
"Viay Singh : 9330938789,\nBijay Singh : 9330938222", 
 
"Nilu :   09830161000,\n09331863222,\n09830071333,\nSantosh Upadhayay :  09831379555,\n09331727858,\n09830593322" 
 
]; 
 

 
var regex = /^([^:0-9\n]+)\s*(?::\s*)?([0-9]*)/gm; 
 
for (var s of strings) { 
 
    console.log("Looking in: ", s, "\n--------------------------"); 
 
\t console.log(s.match(regex)); 
 
} 
 
// To output groups: 
 
console.log("====Outputting groups===="); 
 
for (var s of strings) { 
 
\t while(m=regex.exec(s)) 
 
    console.log(m[1].trim(), ";", m[2]); 
 
}