簡體   English   中英

正則表達式數據值 Javascript 空白

[英]RegEx Data Values Javascript white Space

我正在嘗試為我收到的數據添加正確的空格。 目前它顯示這樣

沒有開始

ReadyforPPPD審查

這是我正在使用的代碼

.replace(/([A-Z])/g, '$1')

“NotStarted”顯示正確的“Not Started”,但“ReadyforPPPDReview”顯示“Readyfor PPPD Review”,當它看起來像這樣“Ready for PPPD Review”時

使用一個正則表達式或 function 處理這兩種方法的最佳方法是什么?

您需要一個 NLP 引擎來正確處理這個問題。 以下是兩種使用簡單正則表達式的方法,它們都有局限性:

1.使用停用詞列表

我們盲目地在停用詞前后添加空格:

 var str = 'NotStarted, ReadyforPPPDReview'; var wordList = 'and, for, in, on, not, review, the'; // stop words var wordListRe = new RegExp('(' + wordList.replace(/, */g, '|') + ')', 'gi'); var result1 = str.replace(wordListRe, ' $1 ') // add space before and after stop words.replace(/([az])([AZ])/g, '$1 $2') // add space between lower case and upper case chars.replace(/ +/g, ' ') // remove excessive spaces.trim(); // remove spaces at start and end console.log('str: ' + str); console.log('result1: ' + result1);

正如您可以想象的那樣,停用詞方法有一些嚴重的局限性。 例如,單詞formula input將導致for mula in put

1.使用映射表

映射表列出了需要分隔的單詞(不涉及葯物),如以下代碼片段所示:

 var str = 'NotStarted, ReadyforPPPDReview'; var spaceWordMap = { NotStarted: 'Not Started', Readyfor: 'Ready for', PPPDReview: 'PPPD Review' // add more as needed }; var spaceWordMapRe = new RegExp('(' + Object.keys(spaceWordMap).join('|') + ')', 'gi'); var result2 = str.replace(spaceWordMapRe, function(m, p1) { // m: matched snippet, p1: first group return spaceWordMap[p1] // replace key in spaceWordMap with its value }).replace(/([az])([AZ])/g, '$1 $2') // add space between lower case and upper case chars.replace(/ +/g, ' ') // remove excessive spaces.trim(); // remove spaces at start and end console.log('str: ' + str); console.log('result2: ' + result2);

如果您有一個確定的單詞列表作為輸入,則此方法適用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM