Example usage for java.util.regex Matcher replaceAll

List of usage examples for java.util.regex Matcher replaceAll

Introduction

In this page you can find the example usage for java.util.regex Matcher replaceAll.

Prototype

public String replaceAll(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces every subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:de.alpharogroup.string.StringExtensions.java

/**
 * Replace each occurences from the search pattern(regex) with the given replace String of the
 * given input String.//from  w ww.j a  v a 2  s. com
 *
 * @param input
 *            the input String that will be changed.
 * @param searchRegexPattern
 *            the search regex pattern
 * @param replace
 *            the String to replace with.
 * @return the resulted string
 */
public static String replaceEach(final String input, final String searchRegexPattern, final String replace) {
    final Pattern pattern = Pattern.compile(searchRegexPattern);
    final Matcher matcher = pattern.matcher(input);
    return matcher.replaceAll(replace);
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param input//w w  w  . j a va  2  s . c o m
 * @return String
 */
public static String unescapeBackslash(String input) {
    String result = input;

    Pattern slashPattern = Pattern.compile("\\\\\\\\");
    Matcher slashMatcher = slashPattern.matcher(result);
    result = slashMatcher.replaceAll("\\\\");

    return result;

}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param input//www .  ja v  a  2  s  . c  om
 * @return String
 */
public static String escapeBackreference(String input) {
    String result = input;

    Pattern slashPattern = Pattern.compile("\\\\");
    Matcher slashMatcher = slashPattern.matcher(result);
    result = slashMatcher.replaceAll("\\\\\\\\");

    Pattern dollarPattern = Pattern.compile("\\$");
    Matcher dollarMatcher = dollarPattern.matcher(result);
    result = dollarMatcher.replaceAll("\\\\\\$");

    return result;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param source//from w  ww.  j a  va 2s  .com
 * @return InputStream
 */
public static InputStream stripDoctype(InputStream source) {
    String result = getInputAsString(new InputStreamReader(source));

    Pattern docDeclPattern = Pattern.compile(DOC_DECL_PATTERN);
    Matcher docDeclMatcher = docDeclPattern.matcher(result);
    result = docDeclMatcher.replaceAll("");

    return new StringBufferInputStream(result);
}

From source file:org.eclipse.php.internal.ui.corext.util.Strings.java

/**
 * Removes all duplicate whitespaces from a given string
 * //from  w ww  . j  av  a  2s . c o m
 * @param string
 * @return the trimmed string
 */
public static String removeDuplicateWhitespaces(String string) {
    Pattern pattern = MagicMemberUtil.WHITESPACE_SEPERATOR;
    Matcher matcher = pattern.matcher(string);
    matcher.find();
    return matcher.replaceAll(" "); //$NON-NLS-1$
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

static String performStaticInclude(String includePatternString, String input) {
    String result = input;//from  w  w  w  .jav a2  s .c  o  m
    boolean matchFound = true;

    Pattern staticIncludePattern = Pattern.compile(includePatternString);
    StringBuffer staticIncludeBuf;

    while (matchFound) {
        matchFound = false;
        staticIncludeBuf = new StringBuffer();
        Matcher staticIncludeMatcher = staticIncludePattern.matcher(result);
        while (staticIncludeMatcher.find()) {
            matchFound = true;
            String args = staticIncludeMatcher.group(1);
            try {
                if (!args.startsWith("/")) {
                    String servletPath = FacesContext.getCurrentInstance().getExternalContext()
                            .getRequestServletPath();
                    String workingDir = servletPath.substring(0, servletPath.lastIndexOf("/"));
                    args = workingDir + "/" + args;
                }
                String includeString = getInputAsString(new InputStreamReader(FacesContext.getCurrentInstance()
                        .getExternalContext().getResource(args).openConnection().getInputStream()));
                //Strip xml declarations from included files
                Pattern xmlDeclPattern = Pattern.compile(XML_DECL_PATTERN);
                Matcher xmlDeclMatcher = xmlDeclPattern.matcher(includeString);
                includeString = xmlDeclMatcher.replaceAll("");

                staticIncludeMatcher.appendReplacement(staticIncludeBuf, escapeBackreference(includeString));
            } catch (Exception e) {
                //an error occurred, just remove the include
                staticIncludeMatcher.appendReplacement(staticIncludeBuf, "");
                if (log.isErrorEnabled()) {
                    log.error("static include failed to include " + args, e);
                }
            }
        }
        staticIncludeMatcher.appendTail(staticIncludeBuf);
        result = staticIncludeBuf.toString();
    }
    return result;
}

From source file:com.fujitsu.dc.test.jersey.box.dav.file.MoveFileHeaderValidateTest.java

/**
     * Etag???./* w ww.  ja v  a 2s.com*/
     * @param etag Etag
     * @return ?
     */
    public static long getEtagVersion(String etag) {
        // version?
        Pattern pattern = Pattern.compile("^\"([0-9]+)-([0-9]+)\"$");
        Matcher m = pattern.matcher(etag);
        return Long.parseLong(m.replaceAll("$1"));
    }

From source file:com.magic.util.StringUtil.java

/**
 * @param str/*from   www. j a  v  a 2  s . c o  m*/
 * @param regex
 * Removes all matches of regex from a str
 */
public static String removeRegex(String str, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);
    return matcher.replaceAll("");
}

From source file:com.untangle.app.web_filter.WebFilterDecisionEngine.java

/**
 * Encode a URL// w w w  .  j  av  a 2 s.  c o m
 * 
 * @param domain
 *        The domain
 * @param uri
 *        The URI
 * @return The encoded URL
 */
private static String encodeUrl(String domain, String uri) {
    // Remote trailing dots from domain
    Matcher matcher = trailingDotsPattern.matcher(domain);
    domain = matcher.replaceAll("");

    String url = domain + uri;

    // Remote trailing dots or slashes from URL
    matcher = trailingDotsSlashesPattern.matcher(url);
    url = matcher.replaceAll("");

    StringBuilder qBuilder = new StringBuilder(url);

    int i;
    int lastDot = 0;

    for (i = 0; i < qBuilder.length(); i++) {

        int numCharsAfterThisOne = (qBuilder.length() - i) - 1;

        // Must insert a null escape to divide long spans
        if (i > lastDot + 59) {
            qBuilder.insert(i, "_-0.");
            lastDot = i + 3;
            i += 4;
        }

        if (qBuilder.charAt(i) == '.') {
            lastDot = i;
        }
        // Take care of the rare, but possible case of _- being in the string
        else if (qBuilder.charAt(i) == '_' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '-') {
            qBuilder.replace(i, i + 2, "_-_-");
            i += 4;
        }
        // Convert / to rfc compliant characters _-.
        else if (qBuilder.charAt(i) == '/') {
            qBuilder.replace(i, i + 1, "_-.");
            lastDot = i + 2;
            i += 3;
        }
        // Convert any dots next to each other
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '.') {
            qBuilder.replace(i, i + 2, "._-2e");
            i += 5;
        }
        // Convert any dots at the end. (these should have already been stripped but the zvelo implementation has this here)
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne == 0) {
            qBuilder.replace(i, i + 1, "_-2e");
            i += 4;
        }
        // Convert : to _--
        else if (qBuilder.charAt(i) == ':') {
            qBuilder.replace(i, i + 1, "_--");
            i += 3;
        }
        // Drop everything after ? or #
        else if (qBuilder.charAt(i) == '?' || qBuilder.charAt(i) == '#') {
            qBuilder.delete(i, qBuilder.length());
            break;
        }
        // Convert %HEXHEX to encoded form
        else if (qBuilder.charAt(i) == '%' && numCharsAfterThisOne >= 2 && _isHex(qBuilder.charAt(i + 1))
                && _isHex(qBuilder.charAt(i + 2))) {
            //String hexString = new String(new char[] {qBuilder.charAt(i+1), qBuilder.charAt(i+2)});
            //char c = (char)( Integer.parseInt( hexString , 16) );
            //System.out.println("HEX: \"" + hexString +"\" -> \"" + Character.toString(c) + "\"");
            qBuilder.replace(i, i + 1, "_-");
            i += 4; // 2 for length of replacement + 2 for the hex characters
        }
        // Convert % charaters to encoded form
        else if (qBuilder.charAt(i) == '%') {
            qBuilder.replace(i, i + 1, "_-25");
            i += 4;
        }
        // Convert any remaining non-RFC characters.
        else if (!_isRfc(qBuilder.charAt(i))) {
            String replaceStr = String.format("_-%02X", ((byte) qBuilder.charAt(i)));
            qBuilder.replace(i, i + 1, replaceStr);
            i += 4;
        }
    }

    return qBuilder.toString();
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

/**
 * Format a region in the supplied source file.
 *
 * @param src The ICompilationUnit./*from  w  ww  . j av  a2 s. co m*/
 * @param kind The kind of code snippet to format.
 * @param offset The starting offset of the region to format.
 * @param length The length of the region to format.
 */
public static void format(ICompilationUnit src, int kind, int offset, int length) throws Exception {
    IBuffer buffer = src.getBuffer();
    String contents = buffer.getContents();
    String delimiter = StubUtility.getLineDelimiterUsed(src);
    DefaultCodeFormatter formatter = new DefaultCodeFormatter(src.getJavaProject().getOptions(true));

    // when the eclipse indent settings differ from vim (tabs vs spaces) then
    // the inserted method's indent may be a bit off. this is a workaround to
    // force reformatting of the code from the start of the line to the start of
    // the next set of code following the new method. Doesn't quite fix indent
    // formatting of methods in nested classes.
    while (offset > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(offset - 1))) {
        offset--;
        length++;
    }
    while ((offset + length) < contents.length()
            && IndentManipulation.isLineDelimiterChar(buffer.getChar(offset + length))) {
        length++;
    }

    TextEdit edits = formatter.format(kind, contents, offset, length, 0, delimiter);
    if (edits != null) {
        int oldLength = contents.length();
        Document document = new Document(contents);
        edits.apply(document);

        String formatted = document.get();

        // jdt formatter can introduce trailing whitespace (javadoc comments), so
        // we'll remove all trailing whitespace from the formatted section.
        length += formatted.length() - oldLength;
        if (offset < (offset + length)) {
            String pre = formatted.substring(0, offset);
            StringBuffer section = new StringBuffer(formatted.substring(offset, offset + length));
            StringBuffer post = new StringBuffer(formatted.substring(offset + length));
            // account for section not ending at a line delimiter
            while (!section.toString().endsWith(delimiter) && post.length() > 0) {
                section.append(post.charAt(0));
                post.deleteCharAt(0);
            }

            Matcher matcher = TRAILING_WHITESPACE.matcher(section);
            String stripped = matcher.replaceAll(StringUtils.EMPTY);

            src.getBuffer().setContents(pre + stripped + post);
        } else {
            src.getBuffer().setContents(formatted);
        }

        if (src.isWorkingCopy()) {
            src.commitWorkingCopy(true, null);
        }
        src.save(null, false);
    }
}