Множественное Regex заменить
Я поражен регулярным выражением. Я думаю, что я дислексичен, когда дело доходит до этих ужасных битов кода. Во всяком случае, должен быть более простой способ сделать это (т.е. перечислить набор замещающих экземпляров в одной строке), кто угодно? Спасибо заранее.
function clean(string) {
string = string.replace(/\@[email protected]/g, '').replace(/}/g, '@[email protected]');
string = string.replace(/\@[email protected]/g, '').replace(/{/g, '@[email protected]');
string = string.replace(/\@[email protected]/g, '').replace(/\"/g, '@[email protected]');
string = string.replace(/\@[email protected]/g, '').replace(/\:/g, '@[email protected]');
string = string.replace(/\@[email protected]/g, '').replace(/\,/g, '@[email protected]');
return string;
}
Ответы
Ответ 1
Вы можете определить либо общую функцию, которая имеет смысл, если вы сможете повторно использовать ее в большем количестве частей вашего кода, тем самым делая ее СУХОЙ. Если у вас нет оснований для определения общего, я бы сжимал только часть, которая очищает последовательности и оставляет другие, заменяя их.
function clean(string) {
string = string.replace(/\@[email protected]|\@[email protected]|\@[email protected]|\@[email protected]|\@[email protected]/g, '')
.replace(/}/g, '@[email protected]').replace(/{/g, '@[email protected]')
.replace(/\"/g, '@[email protected]').replace(/\:/g, '@[email protected]')
.replace(/\,/g, '@[email protected]');
return string;
}
Но будьте осторожны, порядок замены был изменен в этом коде.. хотя кажется, что они могут не повлиять на результат.
Ответ 2
Вы можете использовать функцию замены. Для каждого соответствия функция решает, что она должна быть заменена.
function clean(string) {
// All your regexps combined into one:
var re = /@(~lb~|~rb~|~qu~|~cn~|-cm-)@|([{}":,])/g;
return string.replace(re, function(match,tag,char) {
// The arguments are:
// 1: The whole match (string)
// 2..n+1: The captures (string or undefined)
// n+2: Starting position of match (0 = start)
// n+3: The subject string.
// (n = number of capture groups)
if (tag !== undefined) {
// We matched a tag. Replace with an empty string
return "";
}
// Otherwise we matched a char. Replace with corresponding tag.
switch (char) {
case '{': return "@[email protected]";
case '}': return "@[email protected]";
case '"': return "@[email protected]";
case ':': return "@[email protected]";
case ',': return "@[email protected]";
}
});
}
Ответ 3
Вы можете сделать это следующим образом:
function clean(str) {
var expressions = {
'@[email protected]': '',
'}': '@[email protected]',
// ...
};
for (var key in expressions) {
if (expressions.hasOwnProperty(key)) {
str = str.replace(new RegExp(key, 'g'), expressions[key]);
}
}
return str;
}
Имейте в виду, что порядок свойств объекта не может быть достоверно определен (но большинство реализаций вернут их в порядке определения). Вероятно, вам понадобится несколько таких конструкций, если вам нужно обеспечить определенный порядок.
Ответ 4
Вы можете просто соединить их все в порядке.
function clean(string) {
return string.replace(/\@[email protected]/g, '').replace(/}/g, '@[email protected]')
.replace(/\@[email protected]/g, '').replace(/{/g, '@[email protected]')
.replace(/\@[email protected]/g, '').replace(/\"/g, '@[email protected]')
.replace(/\@[email protected]/g, '').replace(/\:/g, '@[email protected]')
.replace(/\@[email protected]/g, '').replace(/\,/g, '@[email protected]');
}
Ответ 5
... должен быть более простой способ сделать this (т.е. перечислить набор замен экземпляры в одной строке)...
Yum, API-первое мышление. Как насчет...?
var clean = multiReplacer({
"@[email protected]": "",
"@[email protected]": "",
"@[email protected]": "",
"@[email protected]": "",
"@[email protected]": "",
"}": "@[email protected]",
"{": "@[email protected]",
"\\": "@[email protected]",
":": "@[email protected]",
",": "@[email protected]"
});
Сантехника:
// From http://simonwillison.net/2006/Jan/20/escape/
RegExp.escape = function(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
function multiReplacer(replacements)
{
var regExpParts = [];
for (prop in replacements)
{
if (replacements.hasOwnProperty(prop))
{
regExpParts.push(RegExp.escape(prop));
}
}
var regExp = new RegExp(regExpParts.join("|"), 'g');
var replacer = function(match)
{
return replacements[match];
};
return function(text)
{
return text.replace(regExp, replacer);
};
}