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');
你好憤怒的編碼器,謝謝你的評論!你能幫我解決這個問題嗎?我通過例子學得最好。老實說,我正在打磚牆,這讓我發瘋。 –
這個小提琴應該給你一個很好的起點。基礎知識在那裏,但你仍然有一些工作要做,以使其更好。它只是JS的一部分,您可以在Chrome控制檯或系統上運行代碼。 https://jsfiddle.net/p7kh5y49/2/ –