Returns only the pattern portion of fullString, or the entire String if the pattern was not found. - Java java.lang

Java examples for java.lang:String Substring

Description

Returns only the pattern portion of fullString, or the entire String if the pattern was not found.

Demo Code

//package com.java2s;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String patternToExtract = "book;
        String fullString = "java2s.com";
        System.out.println(extract(patternToExtract, fullString));
    }//from  www .j  a v  a  2  s . co m

    private static Map patternCache = new HashMap();

    /**
     * Returns only the patternToRemove portion of fullString, or the entire
     * String if the pattern was not found.
     */

    public static String extract(String patternToExtract, String fullString) {
        String rv = null;
        Pattern p = (Pattern) patternCache.get(patternToExtract);
        if (p == null) {
            p = Pattern.compile(patternToExtract);
            patternCache.put(patternToExtract, p);
        }
        Matcher m = p.matcher(fullString);
        if (m.find()) {
            rv = fullString.substring(m.start(), m.end());
        } else {
            rv = fullString;
        }
        return rv;
    }
}

Related Tutorials