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

192
Visualizações
How can I match atomic elements and their amounts in regex with Javascript?

I wanted to make a tool to parse atomic elements from a formula

so say I started with Ba(Co3Ti)2 + 3BrH20 I would first want to parse each compound in the formula, which is easy enough with let regions = str.replace(/\s/g, '').split(/\+/g);

Now for each compound, I want to identify each element and its numerical "amount" so for the example above, for the first compound, Id want an array like this:

[
 "Ba",
 [
  "Co3",
  "Ti"
 ],
 "2"
]

and if finding sub-compounds within parenthesis isnt possible, then I could work with this:

[
 "Ba",
 "(Co3",
 "Ti)",
 "2"
]

Is this possible with regex? This is what I've come up with in a few minutes..

        let compounds = str.replace(/\s/g, '').split(/\+/g);
        for (var r = 0; r < compounds.length; ++r) {
            let elements = compounds[r]
        }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use

str.match(/\(?(?:[A-Z][a-z]*\d*|\d+)\)?/g)

See the regex demo. Details:

  • \(? - an optional (
  • (?:[A-Z][a-z]*\d*|\d+) - either of the two options:
    • [A-Z][a-z]*\d* - an uppercase letter, then zero or more lowercase letters and then zero or more digits
    • | - or
    • \d+ - one or more digits
  • \)? - an optional ).

See a JavaScript demo:

const str = 'Ba(Co3Ti)2';
const re = /\(?(?:[A-Z][a-z]*\d*|\d+)\)?/g;
let compounds = str.match(re);
console.log(compounds);

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