This option works

private static void replace() { String t = "Мне очень нравится Тайланд*-+"; System.out.println(t.replaceAll("[^а-яА-Я\\s]", "")); } 

But we must take a lot and process, and this option does not work

 private static SortedSet<String> clearSet(SortedSet<String> set) { for (String string : set) { string.replaceAll("[^а-яА-Я\\s]", ""); set2.add(string); } return set2; } 

Question. How to write logic, leaving only letters

  • one
    I think the fact is that you need set2.add(string.replaceAll("[^а-яА-Я\\s]", "")) - Juriy Spb

1 answer 1

String is an immutable class. The replaceAll method does not change the string itself, but returns a new, modified string.

Consider an example:

 String input = "ab"; String result = input.replaceAll("a", ""); System.out.println(input); //выводится "ab", строка не изменилась System.out.println(result); //выводится "b" 

Accordingly, for correction, it is necessary to process the value returned from replaceAll .

To do this, you can declare a variable:

 for (String string : set) { String clearString = string.replaceAll("[^а-яА-Я\\s]", ""); set2.add(clearString); } 

Or simply transfer the result to set2 :

 for (String string : set) { set2.add(string.replaceAll("[^а-яА-Я\\s]", "")); } 
  • Exactly)), thanks ... I knew about String, but ..... By the way, how to throw + in karma? - maxaspire
  • @maxaspire thanks for accepting the answer, that's enough. In theory, replaceAll already accepts regular work. - default locale
  • clear ... new theme for me - maxaspire