解析化学式 [英] Parsing a chemical formula

查看:129
本文介绍了解析化学式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为应用程序编写一个方法,它采用像CH3COOH这样的化学式,并返回一些充满符号的集合。

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将返回[C,H,H,H,C,O,O,H]

CH3COOH would return [C,H,H,H,C,O,O,H]

我已经有了一些有点工作的东西,但它非常复杂并且使用了很多代码都有很多嵌套的if-else结构和循环。

I already have something that is kinda working, but it's very complicated and uses a lot of code with a lot of nested if-else structures and loops.

有没有办法可以通过在String.split中使用某种正则表达式来实现这一点。也许在其他一些出色的简单代码中?

Is there a way I can do this by using some kind of regular expression with String.split or maybe in some other brilliant simple code?

推荐答案

假设它正确大写,方程式中的每个符号都匹配这个正则表达式:

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

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

(对于化学挑战,元素的符号始终为大写字母,后跟可选的小写1或可能为2 - 例如汞的汞)

(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*)

所以是的,从理论上说这将是正则表达式可以帮助的东西。如果您正在处理类似C 6 H 2 (NO 2 3 (CH 3 3 然后你的工作当然有点难......

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...

这篇关于解析化学式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆