For this either SMILES or SELFIES can be used. SELFIES have valency and bond configuration checks by design, so even random strings represent valid molecules. SMILES on the other hand can be sanitized, for example using RDKit. With the extension of SMARTS, substructure matches can be found and thus seemingly molecules containing instable functional groups can be removed.