Reputation: 21
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.
Upvotes: 2
Views: 1878
Reputation: 26809
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
Upvotes: 1
Reputation: 19225
Use a string tokeniser:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
Or alternatively, String.split():
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29
Upvotes: 0
Reputation: 34652
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.
Upvotes: 2
Reputation: 81724
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).
Upvotes: 0
Reputation:
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.
Upvotes: 1