1

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?

gaplus
  • 279
  • 4
  • 15
  • Use a negative lookahead to check that you don't have a lowercase letter after: `(?![a-z])`. See http://www.regular-expressions.info/lookaround.html – Casimir et Hippolyte Apr 09 '14 at 23:17

3 Answers3

2

RegExp(symbol+'(?![a-z])','g'); will match the symbol if it is not followed by a lower case letter

kennebec
  • 102,654
  • 32
  • 106
  • 127
1

Use a negative lookahead. The following will also remove any quantifier it may have:

pattern = new RegExp(symbol + "(?![a-z])" + "\d*", "g");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

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.

CAustin
  • 4,525
  • 13
  • 25