Regular expressions are a powerful tool for manipulating textual information, allowing you to perform the sophisticated processing you describe. Before I explain the solution, let's back up one step ...
Regular expressions are a staple of development. A grammar for matching forms to text, regular expressions are used in Apple development for use with predicates, in validating text entry and more.