I'm trying to get the extension of a filename, but for some reason I can't make split work:
System.out.println(file.getName()); //gNVkN.png
System.out.println(file.getName().split(".").length); //0
What am I doing wrong?
The split() method divides the string at the specified regex and returns an array of substrings.
The RegEx Split processor provides a way to split up the data in an attribute into an array, using a regular expression to define where the splits should occur. Use RegEx Split to split up data where you need a more advanced way of splitting up the data than using delimiters.
split (separator, limit) , if the separator is not in the string, it returns a one-element array with the original string in it.
The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.
split()
takes a regular expression (See split(java.lang.String)), not a separator string to split by. The regular expression "."
means "any single character" (See regex), so it will split on anything leaving nothing in you list. To split on a literal dot use:
file.getName().split("\\.")// \. escapes . in regex \\ escapes \ in Java.String
In general, you can use Pattern.quote(str)
to obtain a regular expression that matches str
literally. (suggested by ramon)
file.getName().split(Pattern.quote("."))
Maybe you should reread the api-doc for split(java.lang.String)
The string you pass in is a regex.
Try using
split("\\.")
You need the double backslash because \.
is an invalid escape in a Java-string. So you need to escape the backslash itself in the javastring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With