You have to use regular expressions. I think that regex are so useful that there is no sense in writing the direct solution to your problem. I would recommend you to get familiar with them and try them out on your own. In the future you will be using regex quite often so there is no sense in cutting corners. Here is a quite good tutorial: http://www.vogella.com/articles/JavaRegularExpressions/article.html