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:net.krautchan.data.KCPosting.java

public String getKcStyledContent() {
    String kcStyledContent = originalContent.replaceAll("<br>", "\n>");
    Matcher kcMatcher = kcLinkPat.matcher(kcStyledContent);
    while (kcMatcher.find()) {
        kcStyledContent = kcMatcher.replaceAll(">>" + kcMatcher.group(1));
    }//from   ww w. ja v  a2s.c  o m
    Matcher spoilerMatcher = spoilerPat.matcher(kcStyledContent);
    while (spoilerMatcher.find()) {
        kcStyledContent = ">>"
                + spoilerMatcher.replaceAll("[spoiler]" + spoilerMatcher.group(1) + "[/spoiler]");
    }
    Matcher quoteMatcher = quotePat.matcher(kcStyledContent);
    while (quoteMatcher.find()) {
        kcStyledContent = quoteMatcher.replaceFirst(quoteMatcher.group(1));
        quoteMatcher = quotePat.matcher(kcStyledContent);
    }
    kcStyledContent = ">" + kcStyledContent;
    return kcStyledContent.trim();
}

From source file:net.solarnetwork.web.support.SimpleXmlView.java

private void writeElement(String name, Map<?, ?> props, Writer out, boolean close,
        ViewResponseAugmentor augmentor) throws IOException {
    out.write('<');
    out.write(name);/*from  w ww  .j  av  a  2 s  . c o  m*/
    if (augmentor != null) {
        augmentor.augmentResponse(out);
    }
    Map<String, Object> nested = null;
    if (props != null) {
        for (Map.Entry<?, ?> me : props.entrySet()) {
            String key = me.getKey().toString();
            Object val = me.getValue();
            if (getPropertySerializerRegistrar() != null) {
                val = getPropertySerializerRegistrar().serializeProperty(name, val.getClass(), props, val);
            }
            if (val instanceof Date) {
                SimpleDateFormat sdf = SDF.get();
                // SimpleDateFormat has no way to create xs:dateTime with tz,
                // so use trick here to insert required colon for non GMT dates
                Date date = (Date) val;
                StringBuilder buf = new StringBuilder(sdf.format(date));
                if (buf.charAt(buf.length() - 1) != 'Z') {
                    buf.insert(buf.length() - 2, ':');
                }
                val = buf.toString();
            } else if (val instanceof Collection) {
                if (nested == null) {
                    nested = new LinkedHashMap<String, Object>(5);
                }
                nested.put(key, val);
                val = null;
            } else if (val instanceof Map<?, ?>) {
                if (nested == null) {
                    nested = new LinkedHashMap<String, Object>(5);
                }
                nested.put(key, val);
                val = null;
            } else if (classNamesAllowedForNesting != null && !(val instanceof Enum<?>)) {
                for (String prefix : classNamesAllowedForNesting) {
                    if (val.getClass().getName().startsWith(prefix)) {
                        if (nested == null) {
                            nested = new LinkedHashMap<String, Object>(5);
                        }
                        nested.put(key, val);
                        val = null;
                        break;
                    }
                }
            }

            if (val != null) {
                // replace & with &amp;
                String attVal = val.toString();
                Matcher matcher = AMP.matcher(attVal);
                attVal = matcher.replaceAll("&amp;");
                attVal = attVal.replace("\"", "&quot;");
                out.write(' ');
                out.write(key);
                out.write("=\"");
                out.write(attVal);
                out.write('"');
            }
        }
    }
    if (close && nested == null) {
        out.write('/');
    }
    out.write('>');
    if (nested != null) {
        for (Map.Entry<String, Object> me : nested.entrySet()) {
            outputObject(me.getValue(), me.getKey(), out, augmentor);
        }
        if (close) {
            closeElement(name, out);
        }
    }
}

From source file:com.photon.phresco.framework.actions.applications.Code.java

public String check() {
    S_LOGGER.debug("Entering Method Code.check()");
    StringBuilder sb = new StringBuilder();
    try {//  w w w  . j  a  v a2  s  .c  o  m
        Properties sysProps = System.getProperties();
        S_LOGGER.debug("Phresco FileServer Value of " + PHRESCO_FILE_SERVER_PORT_NO + " is "
                + sysProps.getProperty(PHRESCO_FILE_SERVER_PORT_NO));
        String phrescoFileServerNumber = sysProps.getProperty(PHRESCO_FILE_SERVER_PORT_NO);

        FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig();
        ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator();
        Project project = administrator.getProject(projectCode);
        String technology = project.getProjectInfo().getTechnology().getId();
        if (TechnologyTypes.IPHONES.contains(technology)) {
            StringBuilder codeValidatePath = new StringBuilder(Utility.getProjectHome());
            codeValidatePath.append(projectCode);
            codeValidatePath.append(File.separatorChar);
            codeValidatePath.append(DO_NOT_CHECKIN_DIR);
            codeValidatePath.append(File.separatorChar);
            codeValidatePath.append(STATIC_ANALYSIS_REPORT);
            codeValidatePath.append(File.separatorChar);
            codeValidatePath.append(INDEX_HTML);
            File indexPath = new File(codeValidatePath.toString());
            if (indexPath.isFile() && StringUtils.isNotEmpty(phrescoFileServerNumber)) {
                sb.append(HTTP_PROTOCOL);
                sb.append(PROTOCOL_POSTFIX);
                sb.append(LOCALHOST);
                sb.append(COLON);
                sb.append(phrescoFileServerNumber);
                sb.append(FORWARD_SLASH);
                sb.append(projectCode);
                sb.append(FORWARD_SLASH);
                sb.append(DO_NOT_CHECKIN_DIR);
                sb.append(FORWARD_SLASH);
                sb.append(STATIC_ANALYSIS_REPORT);
                sb.append(FORWARD_SLASH);
                sb.append(INDEX_HTML);
            } else {
                getHttpRequest().setAttribute(REQ_ERROR, getText(FAILURE_CODE_REVIEW));
            }
        } else {
            String serverUrl = "";
            if (StringUtils.isNotEmpty(frameworkConfig.getSonarUrl())) {
                serverUrl = frameworkConfig.getSonarUrl();
            } else {
                serverUrl = getHttpRequest().getRequestURL().toString();
                StringBuilder tobeRemoved = new StringBuilder();
                tobeRemoved.append(getHttpRequest().getContextPath());
                tobeRemoved.append(getHttpRequest().getServletPath());

                Pattern pattern = Pattern.compile(tobeRemoved.toString());
                Matcher matcher = pattern.matcher(serverUrl);
                serverUrl = matcher.replaceAll("");
            }
            StringBuilder builder = new StringBuilder(Utility.getProjectHome());
            builder.append(projectCode);
            builder.append(File.separatorChar);
            builder.append(POM_XML);
            File pomPath = new File(builder.toString());
            PomProcessor processor = new PomProcessor(pomPath);
            String groupId = processor.getModel().getGroupId();
            String artifactId = processor.getModel().getArtifactId();

            sb.append(serverUrl);
            sb.append(frameworkConfig.getSonarReportPath());
            sb.append(groupId);
            sb.append(COLON);
            sb.append(artifactId);
            try {
                URL sonarURL = new URL(sb.toString());
                HttpURLConnection connection = (HttpURLConnection) sonarURL.openConnection();
                int responseCode = connection.getResponseCode();
                S_LOGGER.info("responseCode === " + responseCode);
                S_LOGGER.debug("Response code value " + responseCode);
                if (responseCode != 200) {
                    getHttpRequest().setAttribute(REQ_ERROR, getText(FAILURE_CODE_REVIEW));
                    S_LOGGER.debug("try APP_CODE....... " + APP_CODE);
                    return APP_CODE;
                }
            } catch (Exception e) {
                S_LOGGER.error(
                        "Entered into catch block of Code.check()" + FrameworkUtil.getStackTraceAsString(e));
                //               new LogErrorReport(e, "Code review");
                getHttpRequest().setAttribute(REQ_ERROR, getText(FAILURE_CODE_REVIEW));
                return APP_CODE;
            }
        }
    } catch (Exception e) {
        S_LOGGER.error("Entered into catch block of Code.check()" + FrameworkUtil.getStackTraceAsString(e));
    }
    getHttpRequest().setAttribute(REQ_PROJECT_CODE, projectCode);
    getHttpRequest().setAttribute(REQ_SONAR_PATH, sb.toString());
    return APP_CODE;
}

From source file:com.adobe.acs.commons.replication.dispatcher.impl.DispatcherFlushRulesImpl.java

/**
 * {@inheritDoc}//  w  w w .  j ava 2  s.  c  o  m
 */
@Override
@SuppressWarnings("squid:S3776")
public final void preprocess(final ReplicationAction replicationAction,
        final ReplicationOptions replicationOptions) throws ReplicationException {
    if (!this.accepts(replicationAction, replicationOptions)) {
        return;
    }

    // Path being replicated
    final String path = replicationAction.getPath();

    // Replication action type occurring
    final ReplicationActionType flushActionType = replicationActionType == null ? replicationAction.getType()
            : replicationActionType;

    ResourceResolver resourceResolver = null;

    try {
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(AUTH_INFO);

        // Flush full content hierarchies
        for (final Map.Entry<Pattern, String[]> entry : this.hierarchicalFlushRules.entrySet()) {
            final Pattern pattern = entry.getKey();
            final Matcher m = pattern.matcher(path);

            if (m.matches()) {
                for (final String value : entry.getValue()) {
                    final String flushPath = m.replaceAll(value);

                    log.debug("Requesting hierarchical flush of associated path: {} ~> {}", path, flushPath);
                    dispatcherFlusher.flush(resourceResolver, flushActionType, false, HIERARCHICAL_FILTER,
                            flushPath);
                }
            }
        }

        // Flush explicit resources using the CQ-Action-Scope ResourceOnly header
        for (final Map.Entry<Pattern, String[]> entry : this.resourceOnlyFlushRules.entrySet()) {
            final Pattern pattern = entry.getKey();
            final Matcher m = pattern.matcher(path);

            if (m.matches()) {
                for (final String value : entry.getValue()) {
                    final String flushPath = m.replaceAll(value);

                    log.debug("Requesting ResourceOnly flush of associated path: {} ~> {}", path,
                            entry.getValue());
                    dispatcherFlusher.flush(resourceResolver, flushActionType, false, RESOURCE_ONLY_FILTER,
                            flushPath);
                }
            }
        }

    } catch (LoginException e) {
        log.error("Error issuing  dispatcher flush rules do to repository login exception: {}", e.getMessage());
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}

From source file:com.github.zdsiyan.maven.plugin.smartconfig.internal.RegexConfigurator.java

@Override
public ByteArrayOutputStream execute(InputStream in, Charset charset, List<PointHandle> pointhandles)
        throws IOException {
    String text = IOUtils.toString(in, charset);

    Pattern pattern;/*from   w w w  .  j  a  v  a 2  s. c  o  m*/
    Matcher matcher;
    for (PointHandle point : pointhandles) {

        pattern = Pattern.compile(point.getExpression());
        matcher = pattern.matcher(text);

        while (matcher.find()) {
            switch (point.getMode()) {
            case insert:
                break;
            case delete:
                break;
            case replace:
            default:
                text = matcher.replaceAll(point.getValue());
                break;
            }
        }
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(text.getBytes(charset));
    return out;
}

From source file:org.codelibs.robot.transformer.impl.XmlTransformer.java

protected String trimSpace(final String value) {
    if (trimSpace) {
        final Matcher matcher = SPACE_PATTERN.matcher(value);
        return matcher.replaceAll(" ").trim();
    }//from ww w .j a va 2s .  c  o m
    return value;
}

From source file:SportsBroadcastsSpeechlet.java

/**
 * Parse JSON-formatted list of events/births/deaths from Wikipedia, extract list of events and
 * split the events into a String array of individual events. Run Regex matchers to make the
 * list pretty by adding a comma after the year to add a pause, and by removing a unicode char.
 * //www .j  a  v a 2  s  .c  o m
 * @param text
 *            the JSON formatted list of events/births/deaths for a certain date
 * @return String array of events for that date, 1 event per element of the array
 */
private ArrayList<String> parseJson(String text) {
    // sizeOf (\nEvents\n) is 10
    text = text.substring(text.indexOf("\\nEvents\\n") + SIZE_OF_EVENTS, text.indexOf("\\n\\n\\nBirths"));
    ArrayList<String> events = new ArrayList<String>();
    if (text.isEmpty()) {
        return events;
    }
    int startIndex = 0, endIndex = 0;
    while (endIndex != -1) {
        endIndex = text.indexOf("\\n", startIndex + DELIMITER_SIZE);
        String eventText = (endIndex == -1 ? text.substring(startIndex) : text.substring(startIndex, endIndex));
        // replace dashes returned in text from Wikipedia's API
        Pattern pattern = Pattern.compile("\\\\u2013\\s*");
        Matcher matcher = pattern.matcher(eventText);
        eventText = matcher.replaceAll("");
        // add comma after year so Alexa pauses before continuing with the sentence
        pattern = Pattern.compile("(^\\d+)");
        matcher = pattern.matcher(eventText);
        if (matcher.find()) {
            eventText = matcher.replaceFirst(matcher.group(1) + ",");
        }
        eventText = "In " + eventText;
        startIndex = endIndex + 2;
        events.add(eventText);
    }
    Collections.reverse(events);
    return events;
}

From source file:org.dspace.app.dav.DAVResource.java

/**
 * Utility to filter out characters illegal XML characters when putting
 * something of random provenance into TEXT element.
 * <p>//from ww  w .  ja  v  a 2s.c o  m
 * See <a href="http://www.w3.org/TR/2004/REC-xml-20040204/#charsets">
 * http://www.w3.org/TR/2004/REC-xml-20040204/#charsets</a> for rules,
 * essentially, anything above 0x20 and 0x09 (\t, HT), 0x0a (\n, NL), 0x0d
 * (\r, CR).
 * <p>
 * FIXME: for now, just replace all control chars with '?' Maybe someday
 * attempt to do something more meaningful, once it's clear what that would
 * be.
 * 
 * @param in the in
 * 
 * @return the string
 */
protected static String filterForXML(String in) {
    final Pattern illegals = Pattern.compile("[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]");
    Matcher m = illegals.matcher(in);
    if (m.find()) {
        return m.replaceAll("?");
    } else {
        return in;
    }
}

From source file:org.codehaus.mojo.license.header.transformer.AbstractFileHeaderTransformer.java

protected String removeSpaces(String str) {
    Matcher matcher = REMOVE_SPACE_PATTERN.matcher(str);
    String result;//from   w  w  w .  jav  a  2  s. co  m
    if (matcher.find()) {
        result = matcher.replaceAll("");
    } else {
        result = str;
    }
    return result;
}

From source file:edu.stanford.muse.util.EmailUtils.java

/**
 * normalizes the given person name, by stripping whitespace at either end, normalizes spaces, so exactly 1 space between tokens.
 * returns null if not a valid name or has a banned word/string or is a single word name
 * retains case of the input as is.//from  w  w w  .j  a  v  a  2 s .c  o  m
 * returns same case
 */
public static String cleanPersonName(String name) {
    // be careful with case, we want name to remain in its original case
    if (name == null)
        return null;
    name = name.trim();

    if (name.indexOf("@") >= 0) // an email addr, not a real name -- we dunno what's happening, just return it as is, just lowercasing it.
        return name.toLowerCase();

    // a surprising number of names in email headers start and end with a single quote
    // if so, strip it.
    if (name.startsWith("'") && name.endsWith("'"))
        name = name.substring(1, name.length() - 1);
    if (name.startsWith("\"") && name.endsWith("\""))
        name = name.substring(1, name.length() - 1);

    // check if it has any characters at all
    boolean allNonAlpha = true;
    for (char c : name.toCharArray()) {
        if (Character.isAlphabetic(c)) {
            allNonAlpha = false;
            break;
        }
    }

    // all non-alphabet? return nothing, because its likely a junk name like "(" or "((" (yes, we see plenty of those!)
    if (allNonAlpha)
        return null;

    // Strip stuff inside parens, e.g. sometimes names are like:
    // foo bar (at home) - or -
    // foo bar [some Dept]
    Matcher m1 = parensPattern.matcher(name);
    name = m1.replaceAll("");
    Matcher m2 = sqBracketsPattern.matcher(name);
    name = m2.replaceAll("");
    name = name.trim();

    // normalize spaces
    // return null if name has banned words - e.g. ben s's email has different people with the "name" (IPM Return requested)
    String result = "";
    for (String t : Util.tokenize(name)) {
        if (DictUtils.bannedWordsInPeopleNames.contains(t.toLowerCase())) {
            if (log.isDebugEnabled())
                log.debug("Will not consider name (because it has a banned word): " + name);
            return null;
        }
        result += t + " ";
    }

    result = result.trim(); // very important, we've added a space after the last token above

    String lowerCaseName = name.toLowerCase();
    for (String bannedString : DictUtils.bannedStringsInPeopleNames)
        if (lowerCaseName.indexOf(bannedString) >= 0) {
            if (log.isDebugEnabled()) {
                log.debug("Will not consider name due to banned string: " + name + " due to string: "
                        + bannedString);
            }
            return null;
        }

    if (Util.tokenize(name).size() < 2) {
        return null; // single word names should not be considered for merging
    }

    return result;
}