Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
Find contents between square brackets and quotations

So to put it straight, lets say I have this string:

command [stuff] [stuff [inside] this] "string" "another [thing] string"

Inside of my code I want to grab all the things with quotation marks and put them in an array and grab all the things inside of outer most brackets (everything inside of the outside brackets) and put them in their own array. Like so:

const string = `command [stuff] [stuff [inside] this] "string" "another [thing] string"`;

let quotations = ["string", "another [thing] string"]
let brackets = ["stuff", "stuff [inside] this"] // I do not want to include any brackets found inside of quotation marks

I have tried to make a regex that would do this, but I am just having a lot of trouble understanding how I would set it up. I did find these two regex which find the stuff in quotations and brackets but they aren't 100% what I am looking for:

// JavaScript Regex
const regexStrings = /(["'])(?:(?=(\\?))\2.)*?\1/g;
const regexBrackets = /\[(.*?)\]/g;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Here's an attempt.

The regex for the quotes will try to find non-quotes between quotes.

The regex for the brackets will first try to match non-quotes between quotes, and then the stuff between brackets.
Then filters out the matches that start with a quote.

There's no recursion, so it's only 1 level of optional brackets within brackets.

const string = `command [stuff] [stuff [inside] this] "string" "another [thing] string"`;

// JavaScript Regex
const regexStrings = /"[^"]*"|'[^']'/g;
const regexBrackets = /"[^"]*"|'[^']'|(\[[^\[\]]*(?:\[[^\[\]]*\])?[^\[\]]*\])/g;

let quotations = string.match(regexStrings)
                       .map(x=>x.replace(/^["']|["']$/g,''));
let brackets = string.match(regexBrackets).filter(x=>!/^["']/.test(x));

console.log(quotations);
console.log(brackets);

To get the multilevel nested brackets, here's an extra tokenizer.

function getQuotesAndBrackets(str) {
 const re = /(["'])(?:\\.|.)*?\1|[\[\]]|[^"'\[\]]+/g;
 let quoted = []; let bracketed = [];
 let token = ''; let cnt = 0; let m;
 let nest = "";
 while(m = re.exec(str)) {
   token = m[0][0];
   if(cnt==0 && /["']/.test(token)) { quoted.push(m[0]) }
   else if(token === '[') { nest += token; cnt += 1 }
   else if(token === ']') { nest += token;
     if(cnt > 1) { cnt -= 1 }
     else { bracketed.push(nest); nest = ""; cnt = 0 }
   }
   else if(cnt > 0) { nest += m[0] }
 }
 return {"quotes":quoted, "brackets":bracketed};
} 

// TEST
const string = `all "the [quoted]" [ stuff [inside ["this"] [bracketed] ] ] "thing" [['blah']]`; 
let quotes_and_brackets = getQuotesAndBrackets(string);

console.log(quotes_and_brackets);

about 4 years ago · Juan Pablo Isaza Relatório

0

There is no support for recursion in JavaScript's regex syntax, so you'll need to throw in some code in order to cope with an arbitrary depth of bracket nesting.

I would therefore go for splitting the string into:

  • quotations (starting and ending with an quotation mark, taking into account backslash escaping)
  • A substring that does not have any of '"[] characters
  • A single [ or ]

Then use a depth counter to keep track how deeply the brackets are so you know when to build a bracket substring by concatenating the tokens along the way.

Here is a snippet, using a bit more complex input string than you provided:

function solve(str) {
    let tokens = str.match(/(['"])((\\.|.)*?)\1|[^[\]'"]+|./g);
    let brackets = [];
    let quotations = [];
    let bracket = "";
    let depth = 0;
    for (let token of tokens) {
        if (token[0] === '"' || token[0] === "'") {
            quotations.push(token.slice(1, -1));
        } else if (token === "[") {
            depth++;
        } else if (token === "]") {
            depth--;
            if (depth < 0) throw "Unbalanced brackets";
            if (!depth) {
                brackets.push(bracket.slice(1));
                bracket = "";
            }
        }
        if (depth) bracket += token;
    }
    if (depth) throw "Unbalanced brackets";
    return {quotations, brackets};
}


const string = String.raw`command [stuff] [stuff [inside [very inside with "escaped \" bracket:]" ]] this] "string" "another [thing] string"`;

console.log(solve(string));

about 4 years ago · Juan Pablo Isaza Relatório

0

Suppose the given string is as follows.

'command [stuff] [stuff [inside] this] "string" "another [thing] string"'
          bbbbb   bbbbbbbbbbbbbbbbbbb   dddddd   dddddddddddddddddddddd         

We wish to extract the values marked bbb... (within brackets) to one array and values marked ddd... (within double-quotes) to a second array. This can be done in two steps.

Step 1: extract all strings within double-quotes and replace those matches, including the surrounding double-quotes, with empty strings

Replace matches of the following regular expression (with the g flag set) with empty strings.1

"([^"]*)"

That will return

'command [stuff] [stuff [inside] this]  '
          bbbbb   bbbbbbbbbbbbbbbbbbb

which we will use in the second step, as shown below.

As well, the contents of capture group 1 will be 'string' and 'another [thing] string', which we must save.

Demo 1

This expression reads, "match a double-quote followed by zero or more characters other than a double-quote, followed by a double-quote, with the sting bounded by the double-quotes saved to capture group 1".

Step 2: extract all strings delimited with brackets that are not within a string that is delimited with brackets

We can obtain the strings of interest ('stuff' and 'stuff [inside] this') by matching the regular expression

(?<=\[)[^\[\]]*(?:\[[^\[\]]*\])?[^\[\]]*(?=\])

Demo 2

This expression can be broken down as follows.

(?<=\[)     # positive lookbehind asserts match is preceded by '['
[^\[\]]*    # match 0+ chars other than '[' and ']'
(?:         # begin non-capture group
  \[        # match '['
  [^\[\]]*  # match 0+ chars other than '[' and ']'
  \]        # match ']'
)?          # end non-capture group and make it optional
[^\[\]]*    # match 0+ chars other than '[' and ']'
(?=\])      # positive lookahead asserts match is followed by ']'

Note that this expression does not work with more than one level of nesting, such as

'[stuff [inside [stuff] like] this]'
  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

The regular expression I've given could be modified to handle up to any given number of levels of nesting by extending the approach I have taken, but it becomes unwieldy for more than three levels of nesting.

1. Alternatively, we could write "(.*?)". Making .* lazy (?) prevents the match from gobbling up characters, including double-quotes, until the last double-quote in the string is reached. If we were to use ".*" (a greedy match) we would obtain the single match, '"string" "another [thing] string'".

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda