Extract string between two strings in java

后端 未结 4 1263
不思量自难忘°
不思量自难忘° 2020-11-27 05:57

I try to get string between <%= and %>, here is my implementation:

String str = \"ZZZZL <%= dsn %> AFFF <%= AFG %>\";
Pattern pattern = Patter         


        
4条回答
  •  孤街浪徒
    2020-11-27 06:42

    Jlordo approach covers specific situation. If you try to build an abstract method out of it, you can face a difficulty to check if 'textFrom' is before 'textTo'. Otherwise method can return a match for some other occurance of 'textFrom' in text.

    Here is a ready-to-go abstract method that covers this disadvantage:

      /**
       * Get text between two strings. Passed limiting strings are not 
       * included into result.
       *
       * @param text     Text to search in.
       * @param textFrom Text to start cutting from (exclusive).
       * @param textTo   Text to stop cuutting at (exclusive).
       */
      public static String getBetweenStrings(
        String text,
        String textFrom,
        String textTo) {
    
        String result = "";
    
        // Cut the beginning of the text to not occasionally meet a      
        // 'textTo' value in it:
        result =
          text.substring(
            text.indexOf(textFrom) + textFrom.length(),
            text.length());
    
        // Cut the excessive ending of the text:
        result =
          result.substring(
            0,
            result.indexOf(textTo));
    
        return result;
      }
    

提交回复
热议问题