Reputation: 289
I'm having trouble writing a function that will take a chemical formula string such as "NiNFe(AsO2)2" and remove one of the elements.
my current attempt is:
pattern = new RegExp(symbol, "g")
formula.replace(pattern, "")
If the symbol is "N" and the formula is "NiNFe(AsO2)2" I end up with "iFe(AsO2)2" instead of the desired "NiFe(AsO2)2". Does anyone know how to code this in such a way that it would distinguish the N from the Ni and replace just that?
Upvotes: 1
Views: 196
Reputation: 4614
If for some reason you want to avoid using negative lookahead (eg. javascript supports it but some other regex engines don't), you could simply match symbol + "([^a-z])"
and replace with $1
.
Upvotes: 0
Reputation: 324750
Use a negative lookahead. The following will also remove any quantifier it may have:
pattern = new RegExp(symbol + "(?![a-z])" + "\d*", "g");
Upvotes: 1
Reputation: 104810
RegExp(symbol+'(?![a-z])','g');
will match the symbol if it is not followed by a lower case letter
Upvotes: 2