Site icon Experiences Unlimited

How to use regular expression in Java?

Regular expressions are very important tool for seraching in text. Below is the code snippet for executing regex search and capturing different parts of the string based on the regular expression

public class RegexTest {

    public static void main(String[] args) {

        String name = "01_My-File.pdf";


    public static void match(String input){
        System.out.println("********* Analysing " + input+" *********");
        String regex = "([0-9]+)([_])(.*)([\\.])([A-Za-z]+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if (!matcher.matches()){
            System.out.println("Input not matches regex");
        System.out.println("Matches: " + matcher.matches());
        String number =;
        System.out.println("Index: " + number);
        String fileName =;
        System.out.println("FileName: " + fileName);
        String extension =;
        System.out.println("Extension: " + extension);

The groups are captured by using (). In the regular expression above ([0-9]+)([_])(.*)([\.])([A-Za-z]+)

We use the Pattern class to compile the regular expression and match the input using it to result in a Matcher instance. This Matcher has information about the result of the regular expression match.

Exit mobile version