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:com.triompha.common.web.html.HtmlUtil.java

/**
 * ?//from  w w  w. java 2s .com
 * 
 * @param s
 * @return
 */
public static String escapeMoreEnter(String s) {
    String regEx = "(<br />)+";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(s);
    return m.replaceAll("<br />");
}

From source file:org.lanes.text.mining.Clustering.java

public String clusterTerms(Map<String, Double> phrasepairs, Map<String, Integer> phrases,
        double avesimnonzero) {
    long timestart = System.currentTimeMillis();

    Map<String, Double> clusters = new HashMap<String, Double>();
    Map<String, Integer> phrasesused = new HashMap<String, Integer>();

    Map<String, Double> sortedlist = MapSorter.sortMap(phrasepairs, "DESC");//MAPPED TO THE LONGEST ONE, MORE SPECIFIC
    Iterator iterator4 = sortedlist.keySet().iterator();
    while (iterator4.hasNext()) {
        String pair = (String) iterator4.next();
        double sim = phrasepairs.get(pair);

        if (sim > 0) {
            Matcher matcherphrase = Pattern.compile("\\[([^\\[\\]]+)\\]\\[([^\\[\\]]+)\\]").matcher(pair);
            if (matcherphrase.find()) {
                String phrase1 = matcherphrase.group(1);
                String phrase2 = matcherphrase.group(2);

                Matcher replace1 = Pattern.compile("_").matcher(phrase1);
                phrase1 = replace1.replaceAll(" ");

                Matcher replace2 = Pattern.compile("_").matcher(phrase2);
                phrase2 = replace2.replaceAll(" ");

                String phraseclustermembership = "NONE-JOIN";
                Map<String, Double> sortedclusters = MapSorter.sortMap(clusters, "DESC");//MAPPED TO THE LONGEST ONE, MORE SPECIFIC
                Iterator iterator5 = sortedclusters.keySet().iterator();
                while (iterator5.hasNext() && phraseclustermembership.equals("NONE-JOIN")) {
                    String clus = (String) iterator5.next();

                    Matcher matcherclus1 = Pattern.compile("\\[" + phrase1 + "\\]").matcher(clus);
                    Matcher matcherclus2 = Pattern.compile("\\[" + phrase2 + "\\]").matcher(clus);
                    boolean found1 = matcherclus1.find();
                    boolean found2 = matcherclus2.find();

                    if (found1 && found2) {
                        phraseclustermembership = "BOTH-JOIN";
                    } else if (!found1 && found2) {
                        phraseclustermembership = "ONE-JOIN{" + phrase2 + "}{" + phrase1 + "}{" + clus + "}";
                    } else if (found1 && !found2) {
                        phraseclustermembership = "ONE-JOIN{" + phrase1 + "}{" + phrase2 + "}{" + clus + "}";
                    }//from  ww  w. ja  v a2  s . co  m
                }

                Matcher matcherstatus = Pattern.compile("^ONE-JOIN").matcher(phraseclustermembership);
                if (phraseclustermembership.equals("NONE-JOIN")) {
                    String[] clustersim = mergePairs(phrases, phrasesused, pair, sim, avesimnonzero);
                    String cluster = clustersim[0];
                    double csim = Double.parseDouble(clustersim[1]);

                    Matcher matcherusedphr = Pattern.compile("\\[([^\\[\\]]+)\\]").matcher(cluster);
                    while (matcherusedphr.find()) {
                        String phr = matcherusedphr.group(1);
                        phrasesused.put(phr, 0);
                    }

                    if (!cluster.equals(pair)) {
                        clusters.put(cluster, csim);
                    }
                } else if (matcherstatus.find() && sim > avesimnonzero) {
                    Matcher extractclus = Pattern.compile("^ONE-JOIN\\{(.+?)\\}\\{(.+?)\\}\\{(.+?)\\}")
                            .matcher(phraseclustermembership);
                    if (extractclus.find()) {
                        String matchingphrase = extractclus.group(1);
                        String nonmatchingphrase = extractclus.group(2);
                        String matchingcluster = extractclus.group(3);
                        String revisedcluster = matchingcluster;

                        phrasesused.put(matchingphrase, 0);
                        phrasesused.put(nonmatchingphrase, 0);

                        Matcher replace = Pattern.compile("\\[" + matchingphrase + "\\]")
                                .matcher(revisedcluster);
                        revisedcluster = replace
                                .replaceAll("[" + matchingphrase + "][" + nonmatchingphrase + "]");

                        Double[] revisedsims = simobj.groupAverageSimilarity(revisedcluster);
                        double revisedsimnonzero = revisedsims[1];

                        clusters.put(revisedcluster, revisedsimnonzero);

                        clusters.remove(matchingcluster);
                    }
                }
            }
        }
    }

    String outliercluster = "";
    Iterator iterator11 = phrases.keySet().iterator();
    while (iterator11.hasNext()) {
        String phr = (String) iterator11.next();

        boolean notfoundincluster = true;
        Iterator iterator9 = clusters.keySet().iterator();
        while (iterator9.hasNext() && notfoundincluster) {
            String clus = (String) iterator9.next();

            Matcher extractphrclus = Pattern.compile("\\[" + phr + "\\]").matcher(clus);
            if (extractphrclus.find()) {
                notfoundincluster = false;
            }
        }
        if (notfoundincluster) {
            outliercluster = outliercluster + "[" + phr + "]";
        }
    }

    if (!outliercluster.equals("")) {
        Double[] outlierclustersims = simobj.groupAverageSimilarity(outliercluster);
        double outlierclustersimnonzero = outlierclustersims[1];
        clusters.put(outliercluster, outlierclustersimnonzero);
    }

    String clusterstr = "";
    Map<String, Double> sortedclusters = MapSorter.sortMap(clusters, "DESC");//MAPPED TO THE LONGEST ONE, MORE SPECIFIC
    Iterator iterator8 = sortedclusters.keySet().iterator();
    while (iterator8.hasNext()) {
        String cluster = (String) iterator8.next();
        double csim = clusters.get(cluster);
        clusterstr = clusterstr + "{<" + csim + ">" + cluster + "}";
    }

    return clusterstr;
}

From source file:org.iplantc.persondir.support.ldap.LdapMultirecordAttributeDao.java

@Override
protected List<IPersonAttributes> getPeopleForQuery(LogicalFilterWrapper queryBuilder, String queryUserName) {
    final String generatedLdapQuery = queryBuilder.encode();

    //If no query is generated return null since the query cannot be run
    if (StringUtils.isBlank(generatedLdapQuery)) {
        return null;
    }/*  w  ww.j a  v a2s.co m*/

    //Insert the generated query into the template if it is configured
    final String ldapQuery;
    if (this.queryTemplate == null) {
        ldapQuery = generatedLdapQuery;
    } else {
        final Matcher queryMatcher = QUERY_PLACEHOLDER.matcher(this.queryTemplate);
        ldapQuery = queryMatcher.replaceAll(generatedLdapQuery);
    }

    //Execute the query
    @SuppressWarnings("unchecked")
    final List<Map<String, List<Object>>> queryResults = this.ldapTemplate.search(this.baseDN, ldapQuery,
            this.searchControls, MAPPER);

    final List<IPersonAttributes> peopleAttributes = new ArrayList<IPersonAttributes>(queryResults.size());
    for (final Map<String, List<Object>> queryResult : queryResults) {
        final IPersonAttributes person;
        if (queryUserName != null) {
            person = new CaseInsensitiveNamedPersonImpl(queryUserName, queryResult);
        } else {
            //Create the IPersonAttributes doing a best-guess at a userName attribute
            final String userNameAttribute = this.getConfiguredUserNameAttribute();
            person = new CaseInsensitiveAttributeNamedPersonImpl(userNameAttribute, queryResult);
        }

        peopleAttributes.add(person);
    }

    return peopleAttributes;
}

From source file:com.predic8.membrane.core.rules.SOAPProxy.java

public void configure() throws Exception {

    parseWSDL();//from ww w .  j a  v  a2s  .  c  o m

    // remove previously added interceptors
    for (; automaticallyAddedInterceptorCount > 0; automaticallyAddedInterceptorCount--)
        interceptors.remove(0);

    // add interceptors (in reverse order) to position 0.

    WebServiceExplorerInterceptor sui = new WebServiceExplorerInterceptor();
    sui.setWsdl(wsdl);
    sui.setPortName(portName);
    interceptors.add(0, sui);
    automaticallyAddedInterceptorCount++;

    boolean hasPublisher = getInterceptorOfType(WSDLPublisherInterceptor.class) != null;
    if (!hasPublisher) {
        WSDLPublisherInterceptor wp = new WSDLPublisherInterceptor();
        wp.setWsdl(wsdl);
        interceptors.add(0, wp);
        automaticallyAddedInterceptorCount++;
    }

    WSDLInterceptor wsdlInterceptor = getInterceptorOfType(WSDLInterceptor.class);
    boolean hasRewriter = wsdlInterceptor != null;
    if (!hasRewriter) {
        wsdlInterceptor = new WSDLInterceptor();
        interceptors.add(0, wsdlInterceptor);
        automaticallyAddedInterceptorCount++;
    }
    if (key.getPath() != null) {
        final String keyPath = key.getPath();
        final String name = URLUtil.getName(router.getUriFactory(), keyPath);
        wsdlInterceptor.setPathRewriter(new PathRewriter() {
            @Override
            public String rewrite(String path2) {
                try {
                    if (path2.contains("://")) {
                        path2 = new URL(new URL(path2), keyPath).toString();
                    } else {
                        Matcher m = relativePathPattern.matcher(path2);
                        path2 = m.replaceAll("./" + name + "?");
                    }
                } catch (MalformedURLException e) {
                }
                return path2;
            }
        });
    }

    if (hasRewriter && !hasPublisher)
        log.warn(
                "A <soapProxy> contains a <wsdlRewriter>, but no <wsdlPublisher>. Probably you want to insert a <wsdlPublisher> just after the <wsdlRewriter>. (Or, if this is a valid use case, please notify us at "
                        + Constants.PRODUCT_CONTACT_EMAIL + ".)");

    if (targetPath != null) {
        RewriteInterceptor ri = new RewriteInterceptor();
        ri.setMappings(Lists.newArrayList(new RewriteInterceptor.Mapping("^" + Pattern.quote(key.getPath()),
                Matcher.quoteReplacement(targetPath), "rewrite")));
        interceptors.add(0, ri);
        automaticallyAddedInterceptorCount++;
    }
}

From source file:AmazonKinesisAuditRecordProcessor.java

public void findFields() {
    String str = "[field1][field2][field3]field4";
    Pattern pattern = Pattern.compile("\\[(.*?)\\]");
    Matcher matcher = pattern.matcher(str);
    List<String> fields = new ArrayList<String>();
    while (matcher.find()) {
        fields.add(matcher.group(1));//  w  w  w. j  a  v  a 2s  . c o  m
    }
    matcher.replaceAll("");
    StringBuffer tail = new StringBuffer();
    matcher.appendTail(tail);
    fields.add(tail.toString());
    System.out.println(fields);
}

From source file:ca.phon.ipadictionary.impl.TransliterationDictionary.java

@Override
public String[] lookup(String orthography) throws IPADictionaryExecption {

    if (preFindPattern != null && preReplaceExpr != null) {
        final Matcher m = preFindPattern.matcher(orthography);
        orthography = m.replaceAll(preReplaceExpr);
    }/*from  ww  w .  ja  v  a2  s . c  o m*/

    final StringBuilder builder = new StringBuilder();
    final Tokenizer tokenizer = createTokenizer();

    try {
        final TokenizerSource source = new StringSource(orthography);
        tokenizer.setSource(source);

        while (tokenizer.hasMoreToken()) {
            final Token token = tokenizer.nextToken();
            if (token.getType() == Token.SPECIAL_SEQUENCE) {
                builder.append(token.getCompanion());
            } else if (token.getType() == Token.NORMAL) {
                // add unknown sequences to return value
                builder.append(token.getImage());

            }
        }
    } catch (TokenizerException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }

    String builderStr = builder.toString();

    if (postFindPattern != null && postReplaceExpr != null) {
        final Matcher m = postFindPattern.matcher(builderStr);
        builderStr = m.replaceAll(postReplaceExpr);
    }

    return new String[] { builderStr };
}

From source file:org.lanes.utility.string.FuzzyMatcher.java

public double getMatchScore() {
    double score = 0.0;

    Matcher replace1 = Pattern.compile("[^\\w]").matcher(matchonx);
    String matchonxnorm = replace1.replaceAll("");

    Matcher replace2 = Pattern.compile("[^\\w]").matcher(longstr);
    String longstrnorm = replace2.replaceAll("");

    boolean isacro = isAcronym(matchonx, shortstr);

    //Matcher matchsubstr = Pattern.compile(matchonx,Pattern.CASE_INSENSITIVE).matcher(matchony);
    //boolean issubstr = matchsubstr.find();

    //System.out.println("scorecompute: (" + matchonxnorm + "," + longstrnorm+ "), isacro(" + matchonx + "," + shortstr + "=" + isacro + ")");

    //issubstr && 
    if (!isacro && !matchonxnorm.equals("") && !longstrnorm.equals("")) {
        double sizereduced = (double) matchonxnorm.length();
        double sizeoriginal = (double) longstrnorm.length();

        score = sizereduced / sizeoriginal;
    } else if (isacro) {
        score = 2.0;//  w w  w.  j  av  a  2 s .  c  o m
    }

    score = Math.round(score * 100.0) / 100.0;

    return score;
}

From source file:org.apereo.services.persondir.support.jdbc.AbstractJdbcPersonAttributeDao.java

@Override
protected PartialWhereClause appendAttributeToQuery(PartialWhereClause queryBuilder, String dataAttribute,
        final List<Object> queryValues) {
    for (final Object queryValue : queryValues) {
        final String queryString = queryValue != null ? queryValue.toString() : null;
        if (StringUtils.isNotBlank(queryString)) {
            if (queryBuilder == null) {
                queryBuilder = new PartialWhereClause();
            } else if (queryBuilder.sql.length() > 0) {
                queryBuilder.sql.append(" ").append(this.queryType.toString()).append(" ");
            }/*  w w w .  j a v  a  2  s.  c o m*/

            //Convert to SQL wildcard
            final Matcher queryValueMatcher = IPersonAttributeDao.WILDCARD_PATTERN.matcher(queryString);
            final String formattedQueryValue = queryValueMatcher.replaceAll("%");

            queryBuilder.arguments.add(formattedQueryValue);
            if (dataAttribute != null) {
                dataAttribute = canonicalizeDataAttributeForSql(dataAttribute);
                queryBuilder.sql.append(dataAttribute);
                if (formattedQueryValue.equals(queryString)) {
                    queryBuilder.sql.append(" = ");
                } else {
                    queryBuilder.sql.append(" LIKE ");
                }
            }
            queryBuilder.sql.append("?");
        }
    }

    return queryBuilder;
}

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

public String view() {
    S_LOGGER.debug("Entering Method Code.view()");
    try {/*www.java2 s.  c  o  m*/
        getHttpRequest().setAttribute(REQ_SELECTED_MENU, APPLICATIONS);
        ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator();
        Project project = administrator.getProject(projectCode);
        getHttpRequest().setAttribute(REQ_PROJECT_CODE, projectCode);
        getHttpRequest().setAttribute(APPLICATION_PROJECT, project);
        FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig();
        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("");
        }
        String sonarReportPath = frameworkConfig.getSonarReportPath();
        String[] sonar = sonarReportPath.split("/");
        serverUrl = serverUrl.concat(FORWARD_SLASH + sonar[1]);
        URL sonarURL = new URL(serverUrl);
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) sonarURL.openConnection();
            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                getHttpRequest().setAttribute(REQ_ERROR, getText(SONAR_NOT_STARTED));
            }
        } catch (Exception e) {
            getHttpRequest().setAttribute(REQ_ERROR, getText(SONAR_NOT_STARTED));
        }
    } catch (Exception e) {
        S_LOGGER.error("Entered into catch block of Code.view()" + FrameworkUtil.getStackTraceAsString(e));
        new LogErrorReport(e, "Code view");
    }
    return APP_CODE;
}

From source file:edu.harvard.i2b2.pm.ws.PMService.java

/**
 * This function is main webservice interface to get pulmonary data from
 * pulmonary report. It uses AXIOM elements(OMElement) to conveniently parse
 * xml messages./*from w w  w  .  ja va2  s .  c o  m*/
 *
 * It excepts incoming request in i2b2 message format, which wraps PFT
 * report inside patientdata object. The response is also will be in i2b2
 * message, which will wrap patientdata object. Patient data object will
 * have all the extracted pft concepts from the report.
 *
 *
 * @param getServices
 * @return OMElement in i2b2message format
 * @throws PortletServiceNotFoundException 
 * @throws PortletServiceUnavailableException 
 * @throws Exception
 */
public OMElement getServices(OMElement getPMDataElement) throws I2B2Exception {

    /*
            
     OMElement returnElement = null;
     String pmDataResponse = null;
     String unknownErrorMessage = "Error message delivered from the remote server \n" +  
     "You may wish to retry your last action";
            
     if (getPMDataElement == null) {
        log.error("Incoming PM request is null");
                
       ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null,
       unknownErrorMessage);
       pmDataResponse = MessageFactory.convertToXMLString(responseMsgType);
        return MessageFactory.createResponseOMElementFromString(pmDataResponse);
     }
             
    ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString());
              
     // String requestElementString = getPMDataElement.toString();
     // childrenDataMsg.setRequestMessageType(requestElementString);
            
      long waitTime = 0;
      if (servicesMsg.getRequestMessageType() != null) {
    if (servicesMsg.getRequestMessageType().getRequestHeader() != null) {
        waitTime = servicesMsg.getRequestMessageType()
                                 .getRequestHeader()
                                 .getResultWaittimeMs();
    }
      }
              
      //do Workplace query processing inside thread, so that  
      // service could send back message with timeout error.     
      ExecutorRunnable er = new ExecutorRunnable();        
      return er.execute(new ServicesHandler(servicesMsg), waitTime);
      */

    OMElement returnElement = null;

    if (getPMDataElement == null) {
        log.error("Incoming PM request is null");
        throw new I2B2Exception("Incoming PM request is null");
    }

    Pattern p = Pattern.compile("<password>.+</password>");
    Matcher m = p.matcher(getPMDataElement.toString());
    String outString = m.replaceAll("<password>*********</password>");

    p = Pattern.compile(">.+</ns9:set_password>");
    m = p.matcher(outString);
    outString = m.replaceAll(">*********</ns9:set_password>");
    log.debug("Received Request PM Element " + outString);

    log.debug("Begin getting servicesMsg");
    ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString());
    long waitTime = 0;

    if (servicesMsg.getRequestMessageType() != null) {
        if (servicesMsg.getRequestMessageType().getRequestHeader() != null) {
            waitTime = servicesMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs();
        }
    }

    log.debug("Completed getting servicesMsg, waittime is: " + waitTime);

    //do PM processing inside thread, so that  
    // service could sends back message with timeout error.

    String pmDataResponse = null;
    try {
        ExecutorRunnable er = new ExecutorRunnable();
        //er.setInputString(requestElementString);
        log.debug("begin setRequestHandler, my servicesMsg: " + servicesMsg);

        er.setRequestHandler(new ServicesHandler(servicesMsg));
        log.debug("middle setRequestHandler");

        log.debug("end setRequestHandler");

        Thread t = new Thread(er);

        ResponseMessageType responseMsgType = null;

        synchronized (t) {
            t.start();

            try {
                //if (waitTime > 0) {
                //   t.wait(waitTime);
                //} else {
                //   t.wait();
                //}

                long startTime = System.currentTimeMillis();
                long deltaTime = -1;
                while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) {
                    if (waitTime > 0) {
                        t.wait(waitTime - deltaTime);
                        deltaTime = System.currentTimeMillis() - startTime;
                    } else {
                        t.wait();
                    }
                }
                pmDataResponse = er.getOutputString();

                if (pmDataResponse == null) {
                    if (er.getJobException() != null) {
                        pmDataResponse = "";
                        throw new I2B2Exception("Portal is not property configured.");
                    } else if (er.isJobCompleteFlag() == false) {
                        String timeOuterror = "Result waittime millisecond <result_waittime_ms> :" + waitTime
                                + " elapsed, try again with increased value";
                        log.debug(timeOuterror);

                        responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror);
                        pmDataResponse = MessageFactory.convertToXMLString(responseMsgType);
                    }
                }
            } catch (InterruptedException e) {
                log.error("Error in thread: " + e.getMessage());

                e.printStackTrace();
                throw new I2B2Exception("Thread error while running PM job " + getPMDataElement, e);
            } finally {
                t.interrupt();
                er = null;
                t = null;
            }
        }

    } catch (Exception e) {
        log.error("Error: " + e.getMessage());
        e.printStackTrace();
    }
    try {
        returnElement = MessageFactory.createResponseOMElementFromString(pmDataResponse);
        log.debug("my pm repsonse is: " + pmDataResponse);
        log.debug("my return is: " + returnElement);
    } catch (XMLStreamException e) {
        log.error("Error creating OMElement from response string " + pmDataResponse, e);
    }

    return returnElement;

}