0

I need to check if a file is an SQL file based off strings for example:

com/cerner/careconcepts/allergy/data/action/sql/ActivityDataReltnQuery.sql

So i guess a regex as follows should be enough? This works in http://regexpal.com/ but not in my code:

fileName.matches(".sql$")

Here is the code where i am trying to find all ".sql" files within a JarFile:

package jarreader;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class processJar {

public static void main(String[] args){

    //File file = new File(".");
    //for(String fileNames : file.list()) System.out.println(fileNames);

    try {
        JarFile jarFile = new JarFile("allergies-2.1.2.jar");
           Enumeration enumeration = jarFile.entries();
           while (enumeration.hasMoreElements())
               getSqlContent(enumeration.nextElement());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static void getSqlContent(Object obj) 
{
  JarEntry entry = (JarEntry)obj;
  String name = entry.getName();

  if(name.matches(".sql$")){
      System.out.println(name);
  }


}
}  

I don't get any output name based on the above regex.

Rookie
  • 5,179
  • 13
  • 41
  • 65
  • Havo you tried to debug your code? Is the filename what you expected? – Jens May 11 '15 at 05:26
  • see also http://stackoverflow.com/questions/234249/java-file-extension-regex?rq=1 –  May 11 '15 at 05:28
  • You may also use `name.toLowerCase().endsWith(".sql");` to avoid using regular expressions. Sometimes i prefer such a way because it's easier to understand if the reg. ex. would get more complex. – chris May 11 '15 at 05:35

1 Answers1

3

In your regex .sql$, . matches a single char and after that it is expecting sql. So it is not matching any name. name.matches(".sql$") should be

name.matches(".*\\.sql$")
Rahul
  • 3,479
  • 3
  • 16
  • 28
  • 1
    I agree with rahul. .* means any character, also more than once. \\. means 'dot' itself. you have to escape the dot with a slash (\\). In a java string you have to escape the slash with a double one (\\\) – chris May 11 '15 at 05:29
  • yes, right understanding. – Rahul May 11 '15 at 05:30
  • Thanks a lot Rahul! That explains it. Do you know how would i tweak this to get the SQL file name? – Rookie May 11 '15 at 05:36
  • You have almost done. You can do it. – Rahul May 11 '15 at 05:38
  • @Rookie: What do you mean with 'tweak this...'? you got the variable `name`. so everything is beautiful – chris May 11 '15 at 05:39
  • I acheived this using String filename = Files.getNameWithoutExtension(path); from the guava library – Rookie May 11 '15 at 05:42