gpt4 book ai didi

javascript - 查找所有以特定字符开头的单词,后跟字符串中的数字

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:43 28 4
gpt4 key购买 nike

我想找到所有以 mc 开头且后跟所有数字的单词

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)

面临的问题:我的代码只返回所有奇怪的发布词我正在使用 Node js

最佳答案

您可以搜索词边界,然后搜索以下字母 mc 和一些数字,后跟另一个词边界。

var string = "hi mc1001 hello mc1002 mc1003 mc1004 amc1005 mc mca mc1234a";

console.log(string.match(/\bmc\d+\b/g));

关于javascript - 查找所有以特定字符开头的单词,后跟字符串中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45455207/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com