由于命名捕获组不是主要问题,因此请重新编写问题。

我有following regex now

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


该代码现在可以正常工作,但是var m = /([a-zA-Z ]*)([0-9]*)/g.exec('Ashok : 9830011245')仅将Ashok作为结果。

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-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--------------------------");
	console.log(s.match(regex));
}
// To output groups:
console.log("====Outputting groups====");
for (var s of strings) {
	while(m=regex.exec(s))
    console.log(m[1].trim(), ";", m[2]);
}

关于javascript - Javascript正则表达式无效组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46316991/

10-09 22:47