I have to write a program that takes a user\'s chemical equation as an input, like 12 CO2 + 6 H2O -> 2 C6H12O6 + 12 O2, and watch if the amount of Atoms is on both sites the
So, every time I need to parse some text with Java
, I mostly end up just using Regex
. So I'd recommend you to also do so.
You can test regular expressions at regex101.com.
And also easily use it in Java
:
final inputText = ...
final Pattern pattern = Patern.compile("Some regex code");
final Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println(matcher.group(0));
}
Inside Regex
you can define capturing groups with (
and )
and then grab the results by matcher.group(int)
.
For example, you may first separate the equation using (.*) -> (.*)
.
Then loop the left and right group using find
with: (\d+) (\w+)(?: \+| -|$)
.
After that you can use group(1)
for the amount and group(2)
for the element.
And if needed also iterate the second group (the element) for the exact element distribution using (\w)(\d?)
. Then the first group is the element, for example for the text CO2
it yields two hits, the first hit has group(1) -> C
and no second group. The second hit has group(1) -> O
and group(2) -> 2
.
Test your regex here: regex101#Q6KMJo