Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for file extensions in Java

Tags:

java

regex

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.

like image 303
MohanVS Avatar asked Jun 24 '16 17:06

MohanVS


1 Answers

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")
like image 194
Pshemo Avatar answered Sep 29 '22 11:09

Pshemo