I have a ListView that display song names and artists. Sometimes, the song names contain the track number and a separator with some in this format
13 - J. Cole - Best Friend
and others like this
13 - Beautiful People
After some digging around I found that the best way to go about this is to define a regex pattern that will remove any unnecessary characters in the string. Cool. I've looked at other SO questions on a similar topic here and a couple blog posts but still no luck.
This my first time dealing with regular expressions and I find it quite useful, just trying to wrap my head around coming up with efficient/useful patterns.
Here's what I need to remove from the string if it is a match
The track number
The "-" or whatever separator character that follows it
The artist name and the "-" that follows that(Each artist name is listed below the song, so it would be redundant)
Any help on this would be greatly appreciated as usual guys, thanks!
Edit: The same output that I would like is something like this, with just the song names. No track numbers, and if applicable; no artist names following the "-"
Beautiful People
Angel of Mine
Human Nature
Here's a possible regex you could use:
name.replaceFirst("^\\d+\\.?\\s*-(?:.*?-)?\\s*", "")
This takes out:
A piece of code will be better to give you a hint:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String[] songNames = {
"1 - my awesome artist - go beyond",
"2 - such is life",
"My awesome song"
};
Pattern trackNumberPattern = Pattern.compile("^ *\\d+ *- *");
Pattern artistPattern = Pattern.compile(" *- *[^-]+ *- *");
Matcher matcher;
for(String song: songNames) {
matcher = trackNumberPattern.matcher(song);
if(matcher.find()) {
song = matcher.replaceFirst("");
}
matcher = artistPattern.matcher(song);
if(matcher.find()) {
song = matcher.replaceFirst("");
}
System.out.println(">>> " + song);
}
}
}
You can find the doc to write regex in java here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
DISCLAIMER: This won't work properly if some of the song names or artist names contain dashes (-), etc...
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