Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!