如果要突出顯示與特定模式不匹配的任何內容,可以使用此代碼。這比試圖修改正則表達式否定匹配更具可擴展性。
function unmatches(regex, str, callback) {
var result = "";
var lastAppend = 0;
var arr;
var nonMatching;
while ((arr = regex.exec(str)) != null) {
nonMatching = str.substring(lastAppend, arr.index);
if (typeof callback === "function") {
nonMatching = callback(nonMatching);
}
// If a function is not supplied, currently, it output back
// the input string. It can be extended, though.
result += nonMatching + arr[0];
lastAppend = arr.index + arr[0].length;
// In case the global flag is not set
// There is at most one match without global flag
if (!regex.global) {
break;
}
}
nonMatching = str.substring(lastAppend);
if (typeof callback === "function") {
nonMatching = callback(nonMatching);
}
result += nonMatching;
return result;
}
使用你的情況作爲例子(注意,我添加了g
標誌):
var result = unmatches(/( )*[ą-źa-z0-9\s]+/g, "dfgtąść45%$#tg ss&k;", function (m) {
if (m === "") {
// Non matching part can be empty string
return m; // Ignore
} else {
// The non-empty string case
return '<span style="color: red;">' + m + '</span>';
}
});
「負」 ......這負:'( )* [A-ZA-z0- 9 \ s] +'把這個[正則表達式測試](http://www.gethifi.com/tools/regex),我想得到否定的結果 – Peter 2013-03-01 09:54:14
'(?!( ))[^±-a- z0-9 \ s] *'這樣比較好,但沒有得到 < - ';' – Peter 2013-03-01 10:28:37