returns the FIRST string in str that is bounded on the left by leftBound, and bounded on the right by rightBound. - Java java.lang

Java examples for java.lang:String End

Description

returns the FIRST string in str that is bounded on the left by leftBound, and bounded on the right by rightBound.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        String leftBound = "b";
        String rightBound = "com";
        System.out.println(getBoundedString(str, leftBound, rightBound));
    }/*from  ww  w . j  ava2s. co  m*/

    /**
     * This returns the FIRST string in str that is bounded on the left by
     * leftBound, and bounded on the right by rightBound. This will return null
     * if the leftBound is not found within str.
     * 
     * <P>
     * If leftBound can't be found this returns null.
     * </P>
     * <P>
     * This rightBound can't be found then this throws a
     * StringIndexOutOfBoundsException.
     * </P>
     * 
     * @param str
     *            the base string that we will search for the bounded string.
     * @param leftBound
     *            the left bound of the string.
     * @param rightBound
     *            the right bound of the string.
     */
    public static String getBoundedString(String str, String leftBound,
            String rightBound) throws RuntimeException {

        if (str == null) {
            throw new RuntimeException("string to parse is null?");
        }
        int startPos = str.indexOf(leftBound);
        if (startPos > -1) {
            startPos = startPos + leftBound.length();
            int endPos = str.indexOf(rightBound, startPos);
            // dp(str+" start:"+startPos+" end:"+endPos);
            if (endPos == -1) {
                throw new RuntimeException("Can't find rightBound: "
                        + rightBound);
            }
            return str.substring(startPos, endPos);
        } else {
            // if no leftBound can be found.. return null... could be in a
            // search n parse type loop?
            // this keeps "no tag"==null different from "tag not formed
            // properly"==StringParsingException
            return null;
        }
    }
}

Related Tutorials