java method to get file extensions summary [regex and string interception]

  • 2020-05-30 20:04:06
  • OfStack

This article illustrates how java gets file extensions. I will share it with you for your reference as follows:

Problem description: there is 1 String type :String imageName = "zy.jpg "; How do I intercept the trailing name after "."?

Solution 1: use regular expressions


package csdnTest;
import java.util.regex.*;
public class CSDNTest
{
  public static void main(String[] ss)
  {
    String s="abc.jpg";
    //String regex=".+?//.(.+)"; That's fine, but I don't think it's as precise as that 
    String regex=".+?//.([a-zA-z]+)";
    Pattern pt=Pattern.compile(regex);
    Matcher mt=pt.matcher(s);
    if(mt.find())
    {
      System.out.println(mt.group(1));
    }
  }
}

Solution 2:

System.out.println(imageName.substring(imageName.lastIndexOf('.')+1));

or

String FileType=imageName.substring(imageName.lastIndexOf('.')+1,imageName.length());

PS: here are two more handy regular expression tools for you to use:

JavaScript regular expression online testing tool:
http://tools.ofstack.com/regex/javascript

Online regular expression generation tool:
http://tools.ofstack.com/regex/create_reg

I hope this article is helpful for you to design java program.


Related articles: