分解成幾個replace
語句(如以下所列)是這樣的我會去了解它(working fiddle)。
的fixBullets
功能將關閉所有的子彈成HTML實體和fixBulletEntities
修復的。我這樣做是因爲我不知道,如果他們是你的源字符串中只是符號字符或HTML實體正常化子彈。
的fixTimes
功能改變「上午09點18分:「進入」9:18上午。 「(否則,fixPeriods
函數使它看起來像」9. 18am「,我確信你不想要。
關於fixCapitalsEndSentence
函數的一個主要警告......這也將字符串轉換爲」WORDS「 WO。的RDS」這可能不是你想要的。
至少,這應該讓你開始...
function fixBullets(text) {
var bullets = /•/g;
return text.replace(bullets, '•');
}
function fixBulletEntities(text) {
var bulletEntities = /•/ig;
text = text.replace(bulletEntities, '. ');
if (text.indexOf('. ') === 0) {
text = text.substring(2);
}
return text;
}
function fixTimes(text) {
var times = /(\d+)[\.:](\d+[ap]m):?/ig;
return text.replace(times, ' $1:$2. ');
}
function fixPeriods(text) {
var periods = /[.](\w+)/g;
return text.replace(periods, '. $1');
}
function fixCapitalsEndSentence(text) {
var capitalsEndSentence = /([A-Z]{2,})([a-z]+)/g;
text = text.replace(capitalsEndSentence, function(match1, match2, match3) {
var len = match2.length - 1;
var newText = match2.substring(0, len) + '. ' + match2.substring(len, len + 1) + match2.substring(len + 1) + match3;
return newText;
});
return text;
}
function fixMultipleSpaces(text) {
var multipleSpaces = /\s+/g;
return text.replace(multipleSpaces, ' ');
}
function fixAll(text) {
text = fixBullets(text);
text = fixBulletEntities(text);
text = fixTimes(text);
text = fixPeriods(text);
text = fixCapitalsEndSentence(text);
text = fixMultipleSpaces(text);
return text;
}
你downvoted我嗎?我不是一個正則表達式親,所以我一當涉及到這些事情時,它有點無知。或許你可以幫助 – 2012-03-22 11:29:15