简体   繁体   中英

Java check one string in other string

I am receiving metainformations in a radio player via ICY.
Here is a short example of how this can look:

die neue welle - Der beste Musikmix aus 4 Jahrzehnten! - WELSHLY ARMS - SANCTUARY - Der Mehr Musik-Arbeitstag mit Benni Rettich  

Another example for the meta information stream would be:

SWR1 Baden Württemberg

or

Welshly Arms - Sanctuary

Now I need to extract the title from there, the problem is that this 'meta-information' string can have any format. What I know:

-I know the complete meta information string as showed in the first code section
-I know the station name, which is delivered by another ICY propertie

The first approach was to check if the string contains the station name (I thought if not, it has to be the title):

private boolean icyInfoContainsTitleInfo() {
    String title = id3Values.get("StreamTitle"); //this is the title string
    String icy = id3Values.get("icy-name");  //this is the station name

    String[] titleSplit = title.split("\\s");
    String[] icySplit = icy.split("\\s");

    for (String a : titleSplit) {
        StringBuilder abuilder = new StringBuilder();
        abuilder.append(a);
        for (String b : icySplit) {
            StringBuilder builder = new StringBuilder();
            builder.append(b);
            if (builder.toString().toLowerCase().contains(abuilder.toString().toLowerCase())) {
                return false;
            }
        }
    }
    return true;
}

But that does not help me if title and station are both present in the title string.
Is there a pattern that matches a string followed by a slash, backslash or a hyphen followed by another string?

Has anyone encountered a similiar problem?

Since you don't have a specification and each station can send a different format. I would not try to find a "perfect" pattern but simply create a mapping to store each station's format regex to recover the title.

First, create a map

Map<String, String> stationPatterns = new HashMap<>();

Them, insert some pattern you know

stationPatterns.put("station1", "(.*)");
stationPatterns.put("station2", "station2 - (.*)");
...

Then, you just need to get this pattern (where you ALWAYS find one capture group).

public String getPattern(String station){
    return stationPatterns.getOrDefault(station, "(.*)"); //Use a default value to get everything)
}

With this, you just need to get a pattern to extract the title from a String .

Pattern pattern = Pattern.compile(getPattern(stationSelected));
Matcher matcher = pattern.matcher(title);
if (matcher.find()) {
    System.out.println("Title : " + matcher.group(1));
} else {
    System.err.println("The title doesn't match the format");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM