我想用以下逻辑创建一个正则表达式:
1.,如果字符串包含T
,则将其替换为空格
2.,如果字符串包含Z
,请删除Z
我已经写了两个正则表达式,但我无法将它们组合起来:
string.replace(/\T/g,' ') && string.replace(/\Z/g,'');
编辑:我希望正则表达式代码更短
答案 0 :(得分:12)
似乎这甚至不需要正则表达式。只需2个链式替换即可。
var str = '[T] and [Z] but not [T] and [Z]';
var result = str.replace('T',' ').replace('Z','');
console.log(result);
然而,简单的replace
仅取代第一次出现
为了取代所有,正则表达式仍然派上用场。通过使用全球g
标志
请注意,字符不会使用\
进行转义。没有必要。
var str = '[T] and [Z] and another [T] and [Z]';
var result = str.replace(/T/g,' ').replace(/Z/g,'');
console.log(result);
// By using regex we could also ignore lower/upper-case. (the i flag)
// Also, if more than 1 letter needs replacement, a character class [] makes it simple.
var str2 = '(t) or (Ⓣ) and (z) or (Ⓩ). But also uppercase (T) or (Z)';
var result2 = str2.replace(/[tⓉ]/gi,' ').replace(/[zⓏ]/gi,'');
console.log(result2);
但是,如果打算处理真正的大字符串,那么性能是否重要? 然后我在another challenge中发现在1个正则表达式替换中使用未命名的回调函数可以证明更快。与使用2个正则表达式替换相比。
可能因为如果它只有1个正则表达式那么它只需要处理一次巨大的字符串。
示例摘录:
console.time('creating big string');
var bigstring = 'TZ-'.repeat(2000000);
console.timeEnd('creating big string');
console.log('bigstring length: '+bigstring.length);
console.time('double replace big string');
var result1 = bigstring.replace(/[t]/gi,'X').replace(/[z]/gi,'Y');
console.timeEnd('double replace big string');
console.time('single replace big string');
var result2 = bigstring.replace(/([t])|([z])/gi, function(m, c1, c2){
if(c1) return 'X'; // if capture group 1 has something
return 'Y';
});
console.timeEnd('single replace big string');
var smallstring = 'TZ-'.repeat(5000);
console.log('smallstring length: '+smallstring.length);
console.time('double replace small string');
var result3 = smallstring.replace(/T/g,'X').replace(/Z/g,'Y');
console.timeEnd('double replace small string');
console.time('single replace small string');
var result4 = smallstring.replace(/(T)|(Z)/g, function(m, c1, c2){
if(c1) return 'X';
return 'Y';
});
console.timeEnd('single replace small string');
答案 1 :(得分:2)
你可以捕获两者,然后决定在回调中做什么:
string.replace(/[TZ]/g,(m => m === 'T' ? '' : ' '));
var string = 'AZorro Tab'
var res = string.replace(/[TZ]/g,(m => m === 'T' ? '' : ' '));
console.log(res)
使用dict替换你也可以:
var string = 'AZorro Tab'
var dict = { T : '', Z : ' '}
var re = new RegExp(`[${ Object.keys(dict).join('') }]`,'g')
var res = string.replace(re,(m => dict[m] ) )
console.log(res)
答案 2 :(得分:2)
你找这样的东西吗?
ES6
var key = {
'T': ' ',
'Z': ''
}
"ATAZATA".replace(/[TZ]/g, (char) => key[char] || '');
香草
"ATAZATA".replace(/[TZ]/g,function (char) {return key[char] || ''});
或
"ATAZATA".replace(/[TZ]/g,function (char) {return char==='T'?' ':''});
答案 3 :(得分:1)
您可以创建一个自定义函数来替换所需的所有字符:
const replaceAll = (text, obj) => {
return [...text].map(each => {
for (const o in obj){
(each == o) ? each = obj[o] : o;
}
return each;
}).join('');
};
replaceAll('abc', {'a':'x', 'b':'y'}); //"xyc"
这是使用string.prototype
的另一种选择:
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"