There is text read from a file in a variable of type String all_text.

It has sections marked like this:

[f1] ВСкст ΠΊΠ°ΠΊΠΎΠΉ-Ρ‚ΠΎ.... [g5] ВСкст Π΄Ρ€ΡƒΠ³ΠΎΠΉ..... 

How to search the text and save (in the variable String part_txt) strings between [f1] and [g5] ?

  • What exactly causes difficulties? Find index of substring in string? Copy a substring from a string? - Vladyslav Matviienko
  • Copy text between [f1] and [g5] into the path_txt variable. Accordingly, be able to find labels of the type [f1] and [g5] in the text. - kaaa

2 answers 2

 public String ReturnStr(String m1, String m2, String text, int startIndex) { int first, second; //Π½Π΅ Ρ€Π°Π±ΠΎΡ‚Π°Π΅ΠΌ с пустыми строками if(m1.length() == 0 || m2.length() == 0 || text.length() == 0) return null; //ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΈΠΌ, Π½Π΅ Π²Ρ‹Ρ…ΠΎΠ΄ΠΈΡ‚ Π»ΠΈ стартовый индСкс Π·Π° ΠΏΡ€Π΅Π΄Π΅Π»Ρ‹ тСкста if( startIndex < 0 || startIndex > text.length()) return null; //Π½Π°Ρ…ΠΎΠ΄ΠΈΠΌ ΠΏΠ΅Ρ€Π²ΡƒΡŽ ΠΌΠ΅Ρ‚ΠΊΡƒ ΠΈ сдвигаСм индСкс Π½Π° Π΄Π»ΠΈΠ½Ρƒ ΠΌΠ΅Ρ‚ΠΊΠΈ first = text.indexOf(m1,startIndex); //Ссли Π½Π°Ρ‡Π°Π»ΡŒΠ½ΠΎΠΉ ΠΌΠ΅Ρ‚ΠΊΠΈ Π½Π΅ нашлось, Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌ null //Π½ΠΎ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ΡŒ 2 строки Π½ΠΈΠΆΠ΅ ΠΈ вСсти отсчСт с Π½Π°Ρ‡Π°Π»Π° тСкста, это ΠΏΠΎ ТСланию if(first < 0)return null;// Π·Π°ΠΌΠ΅Π½ΠΈΡ‚ΡŒ эту строку first += m1.length();// ΠΈ эту Π½Π° if(first < 0) first = 0; //ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΈΠΌ, Π½Π΅ являСтся Π»ΠΈ ΠΌΠ΅Ρ‚ΠΊΠ° ΠΊΠΎΠ½Ρ†ΠΎΠΌ тСкста if(first >= text.length()) return null; //Π½Π°Ρ…ΠΎΠ΄ΠΈΠΌ Π²Ρ‚ΠΎΡ€ΡƒΡŽ ΠΌΠ΅Ρ‚ΠΊΡƒ second = text.indexOf(m2, first); //Ссли нашли Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π½Π°Ρ‡Π°Π»ΡŒΠ½ΡƒΡŽ ΠΌΠ΅Ρ‚ΠΊΡƒ, Π²Ρ‹Ρ€Π΅Π·Π°Ρ‚ΡŒ вСсь тСкст Π΄ΠΎ ΠΊΠΎΠ½Ρ†Π° if(second < 0)return text.substring(first); return text.substring(first, second); } 

Search by any given tags. In general, there is a lot to improve here, it depends on the problem to be solved.

    Try this:

     String text = "[f1] ВСкст ΠΊΠ°ΠΊΠΎΠΉ-Ρ‚ΠΎ.... [g5] [f1] ВСкст Π΄Ρ€ΡƒΠ³ΠΎΠΉ..... [g5]"; Pattern p = Pattern.compile("\\[f1\\](.+?)\\[g5\\]"); Matcher m = p.matcher(text); m.find(); System.out.println(m.group(1)); m.find(); System.out.println(m.group(1)); 

    Conclusion:

     ВСкст ΠΊΠ°ΠΊΠΎΠΉ-Ρ‚ΠΎ.... ВСкст Π΄Ρ€ΡƒΠ³ΠΎΠΉ..... 

    If necessary, go over the entire text, it is obvious, the cycle -> check for a match.

    • one
      Fine! Everything worked out. Thank. - kaaa