I believe what you want is to replace all periods in the file name part with spaces, but keep the extension, right?
If so, something like this would be appropriate:
String[] tests = {
"foo.bar.txt", // [foo bar.txt]
"foo...bar.foo.txt", // [foo bar foo.txt]
"........", // [.]
"...x...dat", // [x.dat]
"foo..txt", // [foo.txt]
"mmm....yummy...txt" // [mmm yummy.txt]
};
for (String test : tests) {
int k = test.lastIndexOf('.');
String s = test.substring(0, k).replaceAll("\\.+", " ").trim()
+ test.substring(k);
System.out.println("[" + s + "]");
}
Essentially the way this works is:
- First, find the
lastIndexOf('.')
in our string
- Say this index is
k
, then we have logically separated our string into:
substring(0, k)
, the prefix part
substring(k)
, the suffix (file extension) part
- Then we use regex on the prefix part to
replaceAll
matches of \.+
with " "
- That is, a literal dot
\.
, repeated one or more times +
- We also
trim()
this string to remove leading and trailing spaces
- The result we want is the transformed prefix concatenated with the original suffix
Clarifications
- The reason why the pattern is
\.+
instead of .+
is because the dot .
is a regex metacharacter, but in this case we really mean a literal period, so it needs to be escaped as \.
- The reason why this pattern as a Java string literal is
"\\.+"
is because \
is itself a Java string literal escape character. For example, the string literal "\t"
contains the tab character. Analogously, the string literal "\\"
contains the backslash character; it has a length()
of one.
References