MohanVS
MohanVS

Reputation: 167

Regular expression for file extensions in Java

I am trying to write a simple regular expression to identify all filenames in a list which end with ".req.copied" extension. The code I am using is given below

public class Regextest {
 public static void main(String[] args) {
    // TODO Auto-generated method stub
 String test1=new String("abcd.req.copied");
  if(test1.matches("(req.copied)?")) {
     System.out.println("Matches");
    }
  else
     System.out.println("Does not Match");
    }

 }

The regex tests ok in online regex testers but does not function in the program. I have tried multiple combinations (like splitting req and copied into two regexes, or literal matching of the dot character) but nothing works (even the simplest regex of (reg)? returned a "Does not Match" output). Please let me know how to tackle this.

Upvotes: 11

Views: 25095

Answers (4)

Pshemo
Pshemo

Reputation: 124275

Main problem with matches here is that it requires from regex to match entire string. But in your case your regex describes only part of it.

If you really want to use matches here your code could look more like

test1.matches(".*\\.req\\.copied")
  • . represents any character (except line separators like \r) so if you want it to represent only dot you need to escape it like \. (in string we need to write it as "\\." because \ has also special meaning there - like creating special characters \r \n \t and so on - so it also requires escaping via additional \).
  • .* will let regex accept any characters before .req.copied

But in your case you should simply use endsWith method

test1.endsWith(".req.copied")

Upvotes: 11

sinclair
sinclair

Reputation: 2861

test1.matches(".*\\.req\\.copied") should do it but in your case you should consider using endsWith() instead of matches.

Upvotes: 2

everag
everag

Reputation: 7672

You should come up with a Regex that would match the whole string format, not a snippet:

String test1= "abcd.req.copied";

if(test1.matches("^.*req\\.copied$")) {
    System.out.println("Matches");
} else {
    System.out.println("Does not Match");
}

Also, your format was using (req.copied)?, which would match any case. Also, . symbol matches any character, so escape it for matching a dot.

Upvotes: 1

user8397947
user8397947

Reputation: 1544

As resueman said in the comments, you don't need a regex for that. You can simply check if each filename endsWith(".req.copied").

if(test1.endsWith(".req.copied")){
    System.out.println("Matches");
}else{
    System.out.println("Does not match");
}

By the way, the above if-else can be replaced with System.out.println(test1.endsWith(".req.copied") ? "Matches" : "Does not match");.

Upvotes: 2

Related Questions