Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove track number from song name?

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
like image 814
Jade Byfield Avatar asked Jun 24 '13 02:06

Jade Byfield


2 Answers

Here's a possible regex you could use:

name.replaceFirst("^\\d+\\.?\\s*-(?:.*?-)?\\s*", "")

This takes out:

  1. digits at the front
  2. optionally followed by a dot
  3. optionally spaces
  4. a hyphen
  5. if a further hyphen is found, then everything up to that
  6. optionally spaces
like image 54
Chris Jester-Young Avatar answered Sep 19 '22 00:09

Chris Jester-Young


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...

like image 41
morgano Avatar answered Sep 20 '22 00:09

morgano