Good day!
In the line, what is in {....} is called a comment. How to remove all comments from the line? Desirable with an explanation. I can only delete 1 comment :(

public static void main(String[] args) { String s = "bla bla {za4em nado } bla bla { za4em nado} bla"; int p = s.indexOf("{"); int t = s.indexOf("}"); String res; if (p == -1) { res = s; } else { res = s.substring(0, p)+ s.substring(t+1); } System.out.println(res); } 
  • Are nested comments allowed? Judging by the form {...} can be very. - avp
  • sort of like allowed. - Andrey2517
  • Comment on @RainRaus. Unfortunately, the limit of comments to the answer, I ended (all the same, this restriction - nonsense ). Yes you are a hero. With such troubles, also think about Java regexps! No, I'm without irony. - With WiFi, I think legs grow from the same place as in the problem with the partition table. Winda does not like to share, believes that it is her and only her iron, and in nature there is no one else. Sue M $, IMHO, meaningless. - avp

1 answer 1

 Pattern pat=Pattern.compile("\\{.*?\\}"); // рСгулярноС Π²Ρ‹Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ поиска ΠΊΠΎΠΌΠΌΠ΅Π½Ρ‚Π°Ρ€ΠΈΠ΅Π² Matcher match=pat.matcher(s); // ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ соотвСтствий ΠΊ строкС s String result=match.replaceAll(""); // замСняСм всС соотвСтствия пустой строкой 
  • So? public static void main (String [] args) {String s = "bla bla {za4em nado} bla bla {za4em nado} bla"; Pattern pat = Pattern.compile ("\\ {. *?}"); Matcher match = pat.matcher (s); String res = match.replaceAll (""); System.out.println (res);}} - Andrey2517
  • A small clarification. If in the line "x {abc} def} x" the comment is considered "abc} def", then the regular expression proposed by @ReinRaus will work correctly. If in this line the comment is "abc", then the regular expression should be like this: "{[^}] *}". Upd: One more. The String class also has a replaceAll (String, String) method. Thus, the code can be reduced to this: String s = "{} {} {}"; s.replaceAll ("{. *?}", ""); - Sinitsyn Artyom
  • @ Andrey2517, so after all, that with nesting, and most importantly the recognition of incorrect nesting? - avp
  • String s = "bla bla {za4em nado} bla bla {za4em nado} bla"; String s0; s0 = s.replaceAll ("\\ {. *?}", ""); System.out.println (s0); - Andrey2517
  • one
    Wow, this is a cant. Thank you) - Andrey2517