import re
regex = re.compile(r"\b(CARBON\b|IRON\b|ZINC\b|\d+(?:\.\d+)?(?:%|\b))|\S", flags=re.MULTILINE)
test_str = ("CARBON 1569\n"
"1.00% IRON 234\n"
"99% CARBON, 1% IRON 181\n"
"98.2% CARBON 1% ZINC 181\n"
"99% CARBON#1% IRON 141\n"
"ASD CARBON 2% IRON RANDOMWORD 23")
subst = "\\1"
result = regex.sub(subst, test_str)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html