[英]Remove and replace characters by regex
我正在嘗試編寫一個正則表達式,使接下來的事情:
_
>用空格替換 +
->如果沒有其他+,請將其刪除(即c++
=> c++
。 c+
-> c
) '
- >刪除它,如果它在該單詞的開始或結束(即Alin's
- > Alin's
。 'Alin's
- > alin's
) &
, -
.
, !
-不要刪除。 我想通過傳遞一次字符串來做到這一點
例如:
Input: "abc's, test_s! & c++ c+ 'Dirty's'. and beautiful'..."
Output: "abc's test s! & c++ c Dirty's. and beautiful..."
說明:
char `'` in `abc's,` stays because `3`
char `,` in `abc's,` was removed because `5`
char `_` in `test_s!` was replaced by space because `1`
char `!` in `test_s!` is not removed because `!`
char `&` is not removed because `4`
char `+` in `c++` is not removed because `2`
char `+` in `c+` was removed because `2`
word: `'Dirty's'.` was replaced to `Dirty's.` because `3` and `4`
char `'` in `beautiful'...` was removed because `3`
char `.` is not removed because of `4`
這是我的javascript
代碼:
var str = "abc's test_s c++ c+ 'Dirty's'. and beautiful";
console.log(str);
str = str.replace(/[_]/g, " ");
str = str.replace(/[^a-zA-Z0-9 &-.!]/g, "");
console.log(str);
這是我的jsfiddle: http : //jsfiddle.net/alonshmiel/LKjYd/4/
我不喜歡我的代碼,因為我確信可以通過在字符串上運行一次來做到這一點。
任何幫助表示贊賞!
function sanitize(str){ return str.replace(/(_)|(\\'\\W|\\'$)|(^\\'|\\W\\')|(\\+\\+)|([a-zA-Z0-9\\ \\&\\-\\.\\!\\'])|(.)/g,function(car,p1,p2,p3,p4,p5,p6){ if(p1) return " "; if(p2) return sanitize(p2.slice(1)); if(p3) return sanitize(p3.slice(0,-1)); if(p4) return p4.slice(0,p4.length-p4.length%2); if(p5) return car; if(p6) return ""; }); } document.querySelector('#sanitize').addEventListener('click',function(){ document.querySelector('#output').innerHTML= sanitize(document.querySelector('#inputString').value); });
#inputString{ width:290px } #sanitize{ background: #009afd; border: 1px solid #1777b7; border:none; color:#fff; cursor:pointer; height: 1.55em; } #output{ background:#ddd; margin-top:5px; width:295px; }
<input id="inputString" type="text" value="abc's test_s! & c++ c+ 'Dirty's'. and beau)'(tiful'..."/> <input id="sanitize" type="button" value="Sanitize it!"" /> <div id="output" ></div>
一些要點:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
因為您需要的替換項可以不同(沒有空格),所以不能使用固定的字符串(由於單遍約束)。 因此,唯一的方法是使用動態替換。
直接方法:
讓我們嘗試找到要刪除的字符,並在某些情況下保留其他字符:
var str = "abc's, test_s! & c++ c+ 'Dirty's'. and beautiful'...";
var re = /[^\w\s&.!'+-]+|\B'+|'+\B|(\+{2,})|\+|'*(_)'*/g;
var result = str.replace(re, function (_, g1, g2) {
if (g1) return g1;
return (g2) ? ' ' : ''; });
console.log(result);
找到下划線時,將定義捕獲組2(回調函數中的g2
)並返回一個空格。
注意:在上面的示例中,單詞“ word”以正則表達式表示(字符類\\w
所以下划線除外[a-zA-Z0-9_]
),但是例如,如果您想更嚴格一些,要排除數字附近的單引號,您需要稍微改變一下模式:
var re = /[^\w\s&.!'+-]+|(_)'*|([^a-z])'+|'+(?![a-z])|(\+{2,})|\+|^'+/gi;
var result = str.replace(re, function (_, g1, g2, g3) {
if (g2) return g2;
if (g3) return g3;
return (g1) ? ' ' : ''; });
請注意以下兩種模式:
這兩種模式由6個或7個子模式交替組成,這些子模式在大多數情況下可以匹配大約1個或2個字符。 請記住,要找到要刪除的字符,這些模式必須在無法替換的每個字符失敗之前測試6或7個替代方案。 這是一項重要的成本,大多數時候不需要替換角色。
有一種方法可以減少這種費用,您可以在這里申請:第一個字符的辨別
這樣做的想法是盡可能避免測試每個子模式。 可以在此處完成此操作,因為並非所有子模式都以字母開頭,因此,如果在開頭添加了前瞻功能,則可以快速跳過字母中的所有字符而不必測試每個子模式。 模式2的示例
var re = /(?=[^a-z])(?:[^\w\s&.!'+-]+|(_)'*|([^a-z])'+|'+(?![a-z])|(\+{2,})|\+|^'+)/gi;
對於第一種模式,您可以跳過更多字符:
var re = /(?=[^a-z0-9\s&.!-])(?:[^\w\s&.!'+-]+|\B'+|'+\B|(\+{2,})|\+|'*(_)'*)/gi;
盡管有這些改進,但是對於一個小的字符串(〜400),這兩種模式仍需要很多步驟(但請注意,這是一個示例字符串,其中包含所有可能的情況) 。
一種更間接的方法:
現在讓我們嘗試另一種方法,該方法包括找到要替換的字符,但是這次要替換所有字符。
var re = /((?:[a-z]+(?:'[a-z]+)*|\+{2,}|[\s&.!-]+)*)(?:(_)|.)?/gi
var result = str.replace(re, function (_, g1, g2) {
return g1 + ((g2) ? ' ' : '' );
});
(請注意,由於(?:a+|b+|c+)*
之后是始終為真的子模式(?:d|e)?
因此無需防止災難性的回溯。此外,整個模式將永遠不會失敗。字符串或其中的位置。)
回調函數捕獲並替換要替換的字符之前的所有字符(允許的內容)並返回。
這樣,完成同一工作所需的步驟減少了2倍以上。
您需要的是鏈接和交替運算符
function customReplace(str){
return str.replace(/_/g, " ").replace(/^'|'$|[^a-zA-Z0-9 &-.!]|\+(?=[^+])/g,"");
}
正則表達式/^'|'$|[^a-zA-Z0-9 &-.!]|\\+(?=[^+])/g
組合了所有需要刪除的內容。 然后將所有_
替換為一個空格,最后返回該空格。
\\+(?=[^+])
查找+
,其后跟隨+
同樣,替換的順序很重要。
試試這個:通過正則表達式/(?!\\b)'|'(?=\\B)|^'|'$|[^\\w\\d\\s&-.!]|\\+(?=[^+])/gm
function sanitize(str) { var re = /(?!\\b)'|'(?=\\B)|^'|'$|[^\\w\\d\\s&-.!]|\\+(?=[^+])/gm; var subst = ''; var tmp = str.replace(re, subst); // remove all condition without (_) var result = tmp.replace("_", " "); // next replace (_) by ( ) space. return result; } document.querySelector('#sanitize').addEventListener('click', function() { document.querySelector('#output').innerHTML = sanitize(document.querySelector('#inputString').value); });
#inputString { width: 290px } #sanitize { background: #009afd; border: 1px solid #1777b7; border: none; color: #fff; cursor: pointer; height: 1.55em; } #output { background: #eee; margin-top: 5px; width: 295px; }
<input id="inputString" type="text" value="abc's test_s! & c++ c+ 'Dirty's'. and beau)'(tiful'..." /> <input id="sanitize" type="button" value="Sanitize it!" /> <div id="output"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.