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
Filenames would include
NCWV1000245.jpg
I would need 1000245
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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) ;
}
}
}
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]
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-)
String base = fileName.substring(0, fileName.indexOf('.'));
String ext = fileName.substring( fileName.indexOf('.') );