Как убрать числа из строки на java?
Мне нужно убрать числа из строки оставить пробелы и все остальные символы и добавить в переменную justWords, что бы при выводе на экран получилась строка:
Just words: JDK has released on September with new features, feature removals and feature deprecations.
Вот мой код:
public class ParseIntegers {
private static final List<String> WORDS = Arrays.asList(
"JDK 17 has released on 14 September 2021 with 10 new features, 2 feature removals and 2 feature deprecations."
.split(" "));
public static void main(String[] args) {
Iterator<String> words = WORDS.iterator();
String justWords = "";
for (String forJustWord : WORDS) {
if (forJustWord.matches("\\D+")) {
}
}
System.out.println("Just words:" + justWords);
}
}
Ответы (1 шт):
Автор решения: Nowhere Man
→ Ссылка
Проще применить к начальной строке операцию String::replaceAll:
String str = "JDK 17 has released on 14 September 2021 with 10 new features, 2 feature removals and 2 feature deprecations.";
String justWords = str.replaceAll("\\d+ ", ""); // убрать цифры и один пробел после них
System.out.println(justWords);
// -> JDK has released on September with new features, feature removals and feature deprecations.
Если нужно проверить и отфильтровать слова в списке WORDS, можно применить Stream API:
String justWords = WORDS.stream()
.filter(s -> s.matches("\\D+")) // или !s.matches("\\d+")
.collect(Collectors.joining(" "));