Your regex is great for entering an input string. Your problem is that you used split() , which expects regex for a completely different purpose. For split() , the regex that you give it matches the delimiters (delimiters) that separate input parts; they do not match the entire input. So in a different situation (not in your situation) you could say
String[] parts = s.split("[\\- ]");
A regular expression matches a single character, which is a dash or space. This way it will look for dashes and spaces in your string and return parts separated by dashes and spaces.
To use your regular expression to match the input string, you need something like this:
String filename = "01. Kodaline - Autopilot.mp3"; String regex = "^(.*)\\.(.*)\\-(.*)\\.(mp3|flac)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(filename); String[] metadata = new String[4]; if (matcher.find()) { metadata[0] = matcher.group(1);
which sets metadata to the lines "01" , " Kodaline " , " Autopilot" , "mp3" , which is close to what you want, except maybe for extra spaces (which you can search in your regular expression). Unfortunately, I do not think that there is a built-in Matcher function that returns all groups in a single array.
(By the way, in your regular expression you donโt need backslashes before - , but they are harmless, so I left them. - usually does not really matter, so it does not need to be escaped. In square brackets, however, a hyphen is used so you have to use backslash if you want to match the character set and the hyphen is one of those so i used backslash in my split example above.)
source share