2017-08-02 81 views
2

我想找到與三菱商事開始,然後是所有的數字只有找到所有的字與特定的字符後跟數字字符串

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

回答

5

您可以搜索單詞邊界,然後搜索以下字母mc和一些數字後跟另一個單詞邊界。

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

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

+0

晚上感謝,我們可以得到mc後面至少有n位數字,我們可以決定n的值例如n = 2 mc45 mc 32443接受但mc9不是 –

+1

您可以添加一個量詞,如'(/ mc \ d { 4,}/g'至少4位數或更多 –

+0

非常感謝你,簡單但功能強大的解決方案:) –

-1

,你可以簡單地使用

/(mc\d+)/g 

匹配所有 「MC」 之後的數字

2

也許這個作品?

\b(mc)\d+\b

,匹配以「MC」啓動和的字母「C」後的數字的任何數都在持續的話。

+1

是的,但請稍微詳細一點(解釋一下你的正則表達式,提供一個片段等)。 – georg

+0

對不起,你是對的。我應該。下次我會更詳細。 – AmoT

相關問題