You can use
to guarantee the use of the same character as in a catch group.
So, set some "limiters" at the beginning of the string, and at the end use
to ensure that you have the same:
var testes = [
'!abba!', '?abba?', '"ab ba"', "'abba'", 'xabbax', '!eu vou falhar?'
];
function filtro(str) {
var match = str.match(/([!?'"x])(.*)()/);
if (!match) return '';
return match[2];
}
console.log(testes.map(filtro));
In cases where you want to use pairs of symbols to open and close a text region, such as {}
, ()
or <>
could be done as follows:
const testes = [
'(abba)', '!eu vou falhar?', '{abba}', '<A>'
];
const separadores = ['{}', '\(\)', '<>'].map(char => {
const abertura = char.slice(0, char.length / 2);
const fecho = char.slice(char.length / 2);
return '(${abertura})([^${fecho}]+)(${fecho})'
}).join('|');
console.log(separadores)
const regex = new RegExp(separadores);
function filtro(str) {
var match = str.match(regex);
match = match && match.filter(Boolean);
if (!match) return '';
return match[2];
}
console.log(testes.map(filtro));