The following method is more reliable (allows a different number of spaces or tweaks between the source and target). For instance. the target may have extra spaces between words, but they will still match.
First, indicate the characters that are allowed as word separators in your string. Then split the source and target strings into tokens using delimiters. Then check to see if the words in your source are found as starting words.
eg. (Java) I used spaces and hyphens as separators
public boolean isValidMatch(String source, String target){ String[] sourceTokens = source.split("[\\s\\-]+"); // split on sequence of //whitespaces or dashes. Two dashes between words will still split //same as one dash. String[] targetTokens = target.split("[\\s\\-]+"); // split similarly if(sourceTokens.length>targetTokens.length){ return false; } for(int i=0;i<souceTokens.length;i++){ if(!sourceTokens[i].equals(targetTokens[i])){ return false; } } return true; }
PS: You might want to add a point. symbol as a separator, if you have the source "Hello World" and the target "Hello World.mp3"; This will not match at the moment, as the regular expression is not split into a dot, but if you add your separator to include the dot, then it will.
source share