Regex: Open and close with the same character and allow more than one type

2

You can get text between two characters that are equal, with the following conditions:

  • The opening character should be the same as the closing character.
  • Allow more than one character type at opening / closing.

Simple example:

/("|')asdasd("|')/

Allows me to get "asdasd" and 'asdasd'

But he also gets "asdasd'

How to make when open with " , allow to close only with " ?

    
asked by anonymous 16.04.2017 / 03:10

2 answers

2

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));
    
16.04.2017 / 08:41
1

See if it is this:

/\(asdasd\)|{asdasd}/g

Explanation in English

    
16.04.2017 / 03:53