找到所有的字与特定的字符后跟数字字符串
问题描述:
我想找到与三菱商事开始,然后是所有的数字只有找到所有的字与特定的字符后跟数字字符串
var myString="hi mc1001 hello mc1002 mc1003 mc1004 mc mca"
要求输出= [mc1001,mc1002,mc1003,mc1004所有字开始]
我的解决办法:
var myRegEx = /(?:^|\s)mc(.*?)(?:\s|$)/g;
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
console.log("string==",string)
while (match = regex.exec(string)) {
console.log("string==",string)
matches.push(match[index]);
}
return matches;
}
var matches = getMatches(myString, myRegEx, 1);
console.log("matches===>",matches)
面临的问题:我的代码返回所有奇数possting话只 我正在使用节点j
答
您可以搜索单词边界,然后搜索以下字母mc
和一些数字后跟另一个单词边界。
var string = "hi mc1001 hello mc1002 mc1003 mc1004 amc1005 mc mca mc1234a";
console.log(string.match(/\bmc\d+\b/g));
答
,你可以简单地使用
/(mc\d+)/g
匹配所有 “MC” 之后的数字
晚上感谢,我们可以得到mc后面至少有n位数字,我们可以决定n的值例如n = 2 mc45 mc 32443接受但mc9不是 –
您可以添加一个量词,如'(/ mc \ d { 4,}/g'至少4位数或更多 –
非常感谢你,简单但功能强大的解决方案:) –