Java String Sub String substringBetween(String s, String part1, String part2)

Here you can find the source of substringBetween(String s, String part1, String part2)

Description

Returns the first instance of String found exclusively between part1 and part2.

License

Open Source License

Parameter

Parameter Description
s The String you want to substring.
part1 The beginning of the String you want to search for.
part2 The end of the String you want to search for.

Return

The String between part1 and part2. If the s does not contain part1 or part2, the method returns null.

Declaration

public static String substringBetween(String s, String part1, String part2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//w  w w  .  j av  a  2 s  .  c om
     * Returns the first instance of String found exclusively between part1 and part2.
     * @param s The String you want to substring.
     * @param part1 The beginning of the String you want to search for.
     * @param part2 The end of the String you want to search for.
     * @return The String between part1 and part2. 
     * If the s does not contain part1 or part2, the method returns null.
     */
    public static String substringBetween(String s, String part1, String part2) {
        String sub = null;

        int i = s.indexOf(part1);
        int j = s.indexOf(part2, i + part1.length());

        if (i != -1 && j != -1) {
            int nStart = i + part1.length();
            sub = s.substring(nStart, j);
        }

        return sub;
    }
}

Related

  1. substringBeforeLastChar(String str, String separator)
  2. substringBeforeLastIgnoreCase(final String target, final String separator)
  3. substringBetween(final String s, final String tag)
  4. substringBetween(final String str, final String startToken, final String endToken)
  5. substringBetween(String line, final String delimiterBefore, final String delimiterAfter)
  6. substringBetween(String s, String part1, String part2)
  7. substringBetween(String source, String strBegin, String strEnd)
  8. substringBetween(String str, String before, String after)
  9. substringBetween(String str, String open, String close)