Metoda ma w tekście wyszukiwać dane słowo ze zbioru słów, które dostaje obiekt zawierający tę metodę. Te słowa tutaj to technologie:
package adhoc;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import junit.framework.TestCase;
public class FinderProgrammingTechnologyInTextTest extends TestCase{
@Test
public void testFind() {
// Given:
Set<String> setOfProgrammingLanguagesToSeek = new HashSet<>();
setOfProgrammingLanguagesToSeek.add("java");
setOfProgrammingLanguagesToSeek.add("perl");
setOfProgrammingLanguagesToSeek.add("c");
setOfProgrammingLanguagesToSeek.add("c++");
// When:
FinderProgrammingTechnologyInText finder = new FinderProgrammingTechnologyInText(
setOfProgrammingLanguagesToSeek);
Set<String> result = finder.find("java8, perl! c++ and other staff");
// Then:
assertTrue(result.contains("java"));
assertTrue(result.contains("perl"));
assertFalse(result.contains("c")); // NIE DZIAŁA!
assertTrue(result.contains("c++"));
}
}
package adhoc;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FinderProgrammingTechnologyInText {
Set<String> setOfTechnologiesToSearch;
public FinderProgrammingTechnologyInText(Set<String> x) {
this.setOfTechnologiesToSearch = x;
}
public Set<String> find(String text) {
Set<String> result = new HashSet<>();
return setOfTechnologiesToSearch.stream()
.filter(x -> Pattern.compile("\\b" + x + "\\d*\\b").matcher(text).find())
.collect(Collectors.toSet());
}
}
Działa dla wszystkich przypadków poza 3 asercją. JAk to nareperować? Myślałem o ignorowaniu +
ale nie wiem jak to zrobić, bo jak dopisuje Pattern.compile("\\b" + x + "^(\\+)\\d*\\b").matcher(text);
to wszystko się kiełbasi.