Link to home
Start Free TrialLog in
Avatar of vcgDevelopers
vcgDevelopers

asked on

parsing a filename in java

I need to parse out a file name into different strings.

Filenames would include

NCWV1000245.jpg

I would need 1000245
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
String fileName = "NCWV1000245.jpg";
String base = fileName.substring(0, fileName.indexOf('.'));
String ext = fileName.substring( fileName.indexOf('.') );
Avatar of KeithWatson
KeithWatson

Assuming your filenames take the form: <some letters><some numbers>.<3 or 4 letters>

then this program will extract the numbers bit using a regular expression:

package com.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegExp {

      public static void main(String[] args) {
            
            Pattern pattern = Pattern.compile("^[A-Za-z]*([0-9]*)\\.[A-Za-z0-9]{3,4}$");
            
            String s = "NCWV1000245.jpg";

            Matcher m = pattern.matcher(s);
            
            if (m.matches()) {
                  String number = m.group(1);
                  System.out.println(number);
            }
     }

}
That said, I've just become a fan of CEHJ's slimmer solution!
LOL - i thought you might ;-)
8-)