1

I want to match a file name as "abc (1).xyz" or "abc (2).xyz" or "abc (3).xyz" and so on, in which abc and xyz (extension) is fixed. Besides, the space+(number) part is optional, i.e. the abc.xyz is also valid.

I have tried the below code, but it didn't returns the success response:

String regex = "abc\\s([0-9])\\.xyz";
        Pattern mather = Pattern.compile(regex);

        if (mather.matcher(fileName).matches()) {
            return true;
        } else {
            return false;
        }

Please suggest any solution for the same. Thanks in advance.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sanat Pandey
  • 4,081
  • 17
  • 75
  • 132

1 Answers1

0

You may use

String regex = "abc(?:\\s+\\([0-9]+\\))?\\.xyz";

It will match:

  • abc - abc
  • (?:\\s+\\([0-9]+\\))? - an optional sequence of:
    • \\s+ - 1+ whitespace chars
    • \\( - a (
    • [0-9]+ - 1+ digits
    • \\) - a )
  • \\.xyz - a .xyz substring.

Since you are using Matcher#matches() method, the whole string match is required (as if the whole pattern was enclosed with ^ and $ anchors, "^abc(?:\\s+\\([0-9]+\\))?\\.xyz$").

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563