# How to I extract the element name of a chemical compound in a string?

Say I have a compound Fe3O4, and I want to separate the name of elements and number. The code I write for separate number is

atomicMassAlloys[Alloy_String] := StringCases[Alloy, DigitCharacter]


But I do not know how to separate the name of element

## 2 Answers

Here is an example of how to work with chemicals the Mathematica way. First we retrieve the entity corresponding to the chemical:

Then, if we don't know them by heart, we check out the available properties for chemicals:

EntityProperties["Chemical"]


This returns a long list of properties. There is one called "element counts" that seems interesting. We try that one:

• Although it answers the question as posed, I'm not sure that this is the best approach. There are an infinite number of chemical compounds, and Mathematica certainly can't recognise them all. In particular, alloys are often non-stoichiometric and do not really make sense to consider as a single chemical substance: the formula is just a sort of average composition. Even for another fairly simple inorganic chemical, let's say cadmium pyrovanadate, I suspect that this method will fail. (But I wasn't able to test it, unfortunately.) – Oleksandr R. Jan 24 '16 at 14:54

An attempt at a purely string-processing approach:

elem = Alternatives @@
Reverse @ SortBy[StringLength] @ Array[ElementData[#, "Symbol"] &, 112];

chem = StringCases[#, e : elem ~~ n : DigitCharacter ... :> {e, n}] /. "" -> "1" &;

chem @ {"Fe3O4", "CH3Cl"}

{{{"Fe", "3"}, {"O", "4"}}, {{"C", 1}, {"H", "3"}, {"Cl", "1"}}}