Parsing a chemical formula

前端 未结 5 834
离开以前
离开以前 2020-12-13 19:52

I\'m trying to write a method for an app that takes a chemical formula like \"CH3COOH\" and returns some sort of collection full of their symbols.

CH3COOH would retu

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 20:53

    Assuming it's correctly capitalised, each symbol in the equation matches this regular expression:

    [A-Z][a-z]*\d*
    

    (For the chemically challenged, an element's symbol is always capital letter followed by optionally a lower case one or possibly two - e.g. Hg for mercury)

    You can capture the element symbol and the number in groups like so:

    ([A-Z][a-z]*)(\d*)
    

    So yes, in theory this would be something regular expressions could help with. If you're dealing with formulae like C6H2(NO2)3(CH3)3 then your job is of course a bit harder...

提交回复
热议问题