2015-12-03 54 views
0

我已經編寫了一段JavaScript代碼,可將一批文本處理爲100個字符的塊,並且可以匹配正則表達式文本(即5個桔子6個蘋果20梨匹配文本)分開。Javascript:每100塊文本運行一個正則表達式匹配函數

我喜歡正則表達式匹配腳本會自動針對每個塊(每100個字符)運行並按順序輸出匹配結果,最好在表格內格式化。

的問題:1)正則表達式匹配功能不會對新組塊的每個字符串被切成100個字符 2)我掙扎循環的正則表達式匹配功能

你的幫助時運行非常感謝。

var str = " Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas Apple Pears Bananas...."; 
 
var chunks = []; 
 
var chunkSize = 100; 
 

 
while (str) { 
 
    if (str.length < chunkSize) { 
 
    chunks.push(str); 
 
    break; 
 
    } else { 
 
    chunks.push(str.substr(0, chunkSize) + total() + "<p></p>"); 
 
    /// I tried to run the regex match function in this line for each new chunk of 100 characters but failed 
 
    str = str.substr(chunkSize); 
 
    } 
 
} 
 

 

 
function getMatches(string, regex, index) { 
 
    index || (index = 1); 
 
    var matches = []; 
 
    var match; 
 
    while (match = regex.exec(string)) { 
 
    matches.push(match[index]); 
 
    } 
 
    return matches; 
 
} 
 

 
function total() { 
 
    var myString = str;/// I'm trying to pick up each new chunks (100 characters) 
 
    var myString; 
 

 
    var myRegEx_apple = /(?:^|\s)apple(.*?)(?:\s|$)/g; 
 
    var matches = getMatches(myString, myRegEx_apple, 1); 
 
    document.getElementById("myRegEx_apple").innerHTML = (matches.length + ' apple matches found' + '\n'); 
 

 
    var myRegEx_pears = /(?:^|\s)pears(.*?)(?:\s|$)/g; 
 
    var matches = getMatches(myString, myRegEx_pears, 1); 
 
    document.getElementById("myRegEx_pears").innerHTML = (matches.length + ' pears matches found' + '\n');

回答

1

好像你沒有嘗試解決您的問題逐步進行。

  1. 你應該設法得到有效的塊,纔去到下一個步驟驗證它。(我也看不清你在你的代碼做正確的地方,對不起,如果我錯過了什麼)。

  2. 迭代塊數組的每個項目,並匹配字符串與每個3項(「蘋果」,「梨」,「香蕉」)。

嘗試使用此功能可以砍下你的字符串中的100個字符塊:

function chop(str){ 
    return str.match(/.{1,100}/g); 
} 

chunks=chop(str); 

你應該得到100字符的字符串數組。從那裏你去第2步。確保你在你的正則表達式中使用'g'標誌(全局標誌)。

+0

你好憤怒的編碼器,謝謝你的評論!你能幫我解決這個問題嗎?我通過例子學得最好。老實說,我正在打磚牆,這讓我發瘋。 –

+0

這個小提琴應該給你一個很好的起點。基礎知識在那裏,但你仍然有一些工作要做,以使其更好。它只是JS的一部分,您可以在Chrome控制檯或系統上運行代碼。 https://jsfiddle.net/p7kh5y49/2/ –