2

I have a number of files and they are all called something like name_version_xyz.ext.

In my Java code I need to extract the name and the version part of the filename. I can accomplish this using lastIndexOf where I look for underscore, but I don't think that's the nicest solution. Can this be done with a regexp somehow?

Note that the "name" part can contain any number of underscores.

jzd
  • 23,473
  • 9
  • 54
  • 76
Mejram
  • 21
  • 2

5 Answers5

2

If you are guaranteed to having the last part of your files named _xyz.ext, then this is really the cleanest way to do it. (If you aren't guaranteed this, then, you will need to figure out something else, of course.)

As the saying goes with regular expressions:

If you solve you a problem with regular expressions, you now have two problems.

JasCav
  • 34,458
  • 20
  • 113
  • 170
1

You could use Regex but I think it is a bit overkill in this case. So I personally would stick with your current solution.

It is working, not too complicated and that's why I don't see any reasons to switch to another approach.

1

If you don't want to use regular expression I think the easiest solution is when you retrieve files and get only part without extension and then:

String file = "blah_blah_version_123";
String[] tmp = file.split("_version_");
System.out.println("name = " + tmp[0]);
System.out.println("version = " + tmp[1]);

Output:

name = blah_blah
version = 123
lukastymo
  • 26,145
  • 14
  • 53
  • 66
0

Yes, the regexp as a Java string would just look something like (untested)

(.+)_(\\d+)_([^_]+)\\.(???)

"name" would be group(1), "version" group(2), xyz is group(3), and ext is group(4).

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186