regular expressions using java.util.regex API- java

How can I create a regular expression to search strings with a given pattern? For example I want to search all strings that match pattern ‘*index.tx?’. Now this should find strings with values index.txt,mainindex.txt and somethingindex.txp.

Pattern pattern = Pattern.compile("*.html");
Matcher m = pattern.matcher("input.html");

This code is obviously not working.

Answer

You need to learn regular expression syntax. It is not the same as using wildcards. Try this:

Pattern pattern = Pattern.compile("^.*index\.tx.$");

There is a lot of information about regular expressions here. You may find the program RegexBuddy useful while you are learning regular expressions.

Leave a Reply

Your email address will not be published. Required fields are marked *