The good news: there is a tool built to solve this exact problem: regular expressions (aka regex)
The bad news: regular expressions are famously frustrating to read and write
Depending on how badly you want the problem solved and how patient you are, using online resources to craft some regular expressions would be the ticket