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:org.fcrepo.server.access.DefaultAccess.java

private String convertToCSV(String list) {
    // make sure values in the list are comma delimited
    if (list == null) {
        return "*";
    }//from  w  w w  . j a  v a 2s  .c om
    String original = list.trim();
    Pattern spaces = Pattern.compile(" ++");
    Matcher m = spaces.matcher(original);
    String interim = m.replaceAll(",");
    Pattern multcommas = Pattern.compile(",++");
    Matcher m2 = multcommas.matcher(interim);
    String csv = m2.replaceAll(",");
    return csv;
}

From source file:org.opencron.common.utils.StringUtils.java

public static String HtmlToTextGb2312(String inputString) {
    if (inputString == null || "".equals(inputString)) {
        return "";
    }/*from ww w  .ja v a 2s.c  o m*/
    String htmlStr = inputString; // ?html
    String textStr = "";
    Pattern p_script;
    Matcher m_script;
    Pattern p_style;
    Matcher m_style;
    Pattern p_html;
    Matcher m_html;
    Pattern p_houhtml;
    Matcher m_houhtml;
    Pattern p_spe;
    Matcher m_spe;
    Pattern p_blank;
    Matcher m_blank;
    Pattern p_table;
    Matcher m_table;
    Pattern p_enter;
    Matcher m_enter;

    try {
        String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?/[\\s]*?script[\\s]*?>";
        // script?.
        String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?/[\\s]*?style[\\s]*?>";
        // style?.
        String regEx_html = "<[^>]+>";
        // HTML?
        String regEx_houhtml = "/[^>]+>";
        // HTML?
        String regEx_spe = "\\&[^;]+;";
        // ??
        String regEx_blank = " +";
        // ?
        String regEx_table = "\t+";
        // ?
        String regEx_enter = "\n+";
        // ?

        p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // script

        p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // style

        p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // html

        p_houhtml = Pattern.compile(regEx_houhtml, Pattern.CASE_INSENSITIVE);
        m_houhtml = p_houhtml.matcher(htmlStr);
        htmlStr = m_houhtml.replaceAll(""); // html

        p_spe = Pattern.compile(regEx_spe, Pattern.CASE_INSENSITIVE);
        m_spe = p_spe.matcher(htmlStr);
        htmlStr = m_spe.replaceAll(""); // ?

        p_blank = Pattern.compile(regEx_blank, Pattern.CASE_INSENSITIVE);
        m_blank = p_blank.matcher(htmlStr);
        htmlStr = m_blank.replaceAll(" "); // 

        p_table = Pattern.compile(regEx_table, Pattern.CASE_INSENSITIVE);
        m_table = p_table.matcher(htmlStr);
        htmlStr = m_table.replaceAll(" "); // 

        p_enter = Pattern.compile(regEx_enter, Pattern.CASE_INSENSITIVE);
        m_enter = p_enter.matcher(htmlStr);
        htmlStr = m_enter.replaceAll(" "); // 

        textStr = htmlStr;

    } catch (Exception e) {
        System.err.println("Html2Text: " + e.getMessage());
    }

    return textStr;// 
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java

/**
 * Formats the given <code>description</code>. Removes all carriage return characters and replaces
 * wiki links. Finally, the string is trimmed to {@link #MAXIMUM_CELL_LENGTH} characters, if it
 * was longer./*from w w  w.  jav  a2s  .co  m*/
 * 
 * @param description
 *          Input description string
 * @return the formated string or an empty string, if no match could be found.
 */
protected String formatString(String description) {
    if (description == null) {
        return ("");
    }

    String myDescription = description.replaceAll("\r", "");
    Matcher matcher = this.urlPattern.matcher(myDescription);
    String markupFreeString = matcher.replaceAll("$1");
    if (markupFreeString.length() <= MAXIMUM_CELL_LENGTH) {
        return markupFreeString;
    }

    String trimmedString = markupFreeString.substring(0, MAXIMUM_CELL_LENGTH);
    return trimmedString + " ... [truncated]";
}

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();/* w w  w . j a  v  a 2  s. c o m*/
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, ldapUrl);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}

From source file:com.fujitsu.dc.core.rs.odata.AbstractODataResource.java

/**
 * ???TimeMillis??????./*from   w  w w .j ava 2 s.c o m*/
 * @param timeStr TimeMillis??(ex."/Data(...)/", "SYSUTCDATETIME()")
 * @return TimeMillis?
 */
private long getTimeMillis(String timeStr) {
    long timeMillis = 0;
    if (timeStr.equals(Common.SYSUTCDATETIME)) {
        timeMillis = currentTimeMillis;
    } else {
        try {
            Pattern pattern = Pattern.compile("^/Date\\((.+)\\)/$");
            Matcher match = pattern.matcher(timeStr);
            if (match.matches()) {
                String date = match.replaceAll("$1");
                timeMillis = Long.parseLong(date);
            }
        } catch (NumberFormatException e) {
            throw DcCoreException.OData.JSON_PARSE_ERROR.reason(e);
        }
    }
    return timeMillis;
}

From source file:org.apache.ctakes.ytex.uima.annotators.NegexAnnotator.java

private void checkNegation2(JCas aJCas, Sentence s, IdentifiedAnnotation ne, boolean negPoss) {
    // Sorter s = new Sorter();
    String sToReturn = "";
    String sScope = "";
    // String sentencePortion = "";
    // ArrayList sortedRules = null;

    String filler = "_";
    // boolean negationScope = true;

    // Sort the rules by length in descending order.
    // Rules need to be sorted so the longest rule is always tried to match
    // first./*w w  w. j  a v a  2 s. c  om*/
    // Some of the rules overlap so without sorting first shorter rules
    // (some of them POSSIBLE or PSEUDO)
    // would match before longer legitimate negation rules.
    //

    // There is efficiency issue here. It is better if rules are sorted by
    // the
    // calling program once and used without sorting in GennegEx.
    // sortedRules = this.rules;

    // Process the sentence and tag each matched negation
    // rule with correct negation rule tag.
    //
    // At the same time check for the phrase that we want to decide
    // the negation status for and
    // tag the phrase with [PHRASE] ... [PHRASE]
    // In both the negation rules and in the phrase replace white space
    // with "filler" string. (This could cause problems if the sentences
    // we study has "filler" on their own.)

    // Sentence needs one character in the beginning and end to match.
    // We remove the extra characters after processing.
    // vng String sentence = "." + sentenceString + ".";
    String sentence = "." + s.getCoveredText() + ".";

    // Tag the phrases we want to detect for negation.
    // Should happen before rule detection.
    // vng String phrase = phraseString;
    String phrase = ne.getCoveredText();
    Pattern pph = Pattern.compile(phrase.trim(), Pattern.CASE_INSENSITIVE);
    Matcher mph = pph.matcher(sentence);
    CharBuffer buf = CharBuffer.wrap(sentence.toCharArray());

    while (mph.find() == true) {
        sentence = mph.replaceAll(" [PHRASE]" + mph.group().trim().replaceAll(" ", filler) + "[PHRASE]");
    }

    for (NegexRule rule : this.listNegexRules) {
        Matcher m = rule.getPattern().matcher(sentence);
        while (m.find() == true) {
            sentence = m.replaceAll(
                    " " + rule.getTag() + m.group().trim().replaceAll(" ", filler) + rule.getTag() + " ");
        }
    }

    // Exchange the [PHRASE] ... [PHRASE] tags for [NEGATED] ... [NEGATED]
    // based of PREN, POST rules and if flag is set to true
    // then based on PREP and POSP, as well.

    // Because PRENEGATION [PREN} is checked first it takes precedent over
    // POSTNEGATION [POST].
    // Similarly POSTNEGATION [POST] takes precedent over POSSIBLE
    // PRENEGATION [PREP]
    // and [PREP] takes precedent over POSSIBLE POSTNEGATION [POSP].

    Pattern pSpace = Pattern.compile("[\\s+]");
    String[] sentenceTokens = pSpace.split(sentence);
    StringBuilder sb = new StringBuilder();

    // Check for [PREN]
    for (int i = 0; i < sentenceTokens.length; i++) {
        sb.append(" " + sentenceTokens[i].trim());
        if (sentenceTokens[i].trim().startsWith("[PREN]")) {

            for (int j = i + 1; j < sentenceTokens.length; j++) {
                if (sentenceTokens[j].trim().startsWith("[CONJ]")
                        || sentenceTokens[j].trim().startsWith("[PSEU]")
                        || sentenceTokens[j].trim().startsWith("[POST]")
                        || sentenceTokens[j].trim().startsWith("[PREP]")
                        || sentenceTokens[j].trim().startsWith("[POSP]")) {
                    break;
                }

                if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                    sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[NEGATED]");
                }
            }
        }
    }

    sentence = sb.toString();
    pSpace = Pattern.compile("[\\s+]");
    sentenceTokens = pSpace.split(sentence);
    StringBuilder sb2 = new StringBuilder();

    // Check for [POST]
    for (int i = sentenceTokens.length - 1; i > 0; i--) {
        sb2.insert(0, sentenceTokens[i] + " ");
        if (sentenceTokens[i].trim().startsWith("[POST]")) {
            for (int j = i - 1; j > 0; j--) {
                if (sentenceTokens[j].trim().startsWith("[CONJ]")
                        || sentenceTokens[j].trim().startsWith("[PSEU]")
                        || sentenceTokens[j].trim().startsWith("[PREN]")
                        || sentenceTokens[j].trim().startsWith("[PREP]")
                        || sentenceTokens[j].trim().startsWith("[POSP]")) {
                    break;
                }

                if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                    sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[NEGATED]");
                }
            }
        }
    }
    sentence = sb2.toString();

    // If POSSIBLE negation is detected as negation.
    // negatePossible being set to "true" then check for [PREP] and [POSP].
    if (negPoss == true) {
        pSpace = Pattern.compile("[\\s+]");
        sentenceTokens = pSpace.split(sentence);

        StringBuilder sb3 = new StringBuilder();

        // Check for [PREP]
        for (int i = 0; i < sentenceTokens.length; i++) {
            sb3.append(" " + sentenceTokens[i].trim());
            if (sentenceTokens[i].trim().startsWith("[PREP]")) {

                for (int j = i + 1; j < sentenceTokens.length; j++) {
                    if (sentenceTokens[j].trim().startsWith("[CONJ]")
                            || sentenceTokens[j].trim().startsWith("[PSEU]")
                            || sentenceTokens[j].trim().startsWith("[POST]")
                            || sentenceTokens[j].trim().startsWith("[PREN]")
                            || sentenceTokens[j].trim().startsWith("[POSP]")) {
                        break;
                    }

                    if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                        sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[POSSIBLE]");
                    }
                }
            }
        }
        sentence = sb3.toString();
        pSpace = Pattern.compile("[\\s+]");
        sentenceTokens = pSpace.split(sentence);
        StringBuilder sb4 = new StringBuilder();

        // Check for [POSP]
        for (int i = sentenceTokens.length - 1; i > 0; i--) {
            sb4.insert(0, sentenceTokens[i] + " ");
            if (sentenceTokens[i].trim().startsWith("[POSP]")) {
                for (int j = i - 1; j > 0; j--) {
                    if (sentenceTokens[j].trim().startsWith("[CONJ]")
                            || sentenceTokens[j].trim().startsWith("[PSEU]")
                            || sentenceTokens[j].trim().startsWith("[PREN]")
                            || sentenceTokens[j].trim().startsWith("[PREP]")
                            || sentenceTokens[j].trim().startsWith("[POST]")) {
                        break;
                    }

                    if (sentenceTokens[j].trim().startsWith("[PHRASE]")) {
                        sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[POSSIBLE]");
                    }
                }
            }
        }
        sentence = sb4.toString();
    }

    // Remove the filler character we used.
    sentence = sentence.replaceAll(filler, " ");

    // Remove the extra periods at the beginning
    // and end of the sentence.
    sentence = sentence.substring(0, sentence.trim().lastIndexOf('.'));
    sentence = sentence.replaceFirst(".", "");

    // Get the scope of the negation for PREN and PREP
    if (sentence.contains("[PREN]") || sentence.contains("[PREP]")) {
        int startOffset = sentence.indexOf("[PREN]");
        if (startOffset == -1) {
            startOffset = sentence.indexOf("[PREP]");
        }

        int endOffset = sentence.indexOf("[CONJ]");
        if (endOffset == -1) {
            endOffset = sentence.indexOf("[PSEU]");
        }
        if (endOffset == -1) {
            endOffset = sentence.indexOf("[POST]");
        }
        if (endOffset == -1) {
            endOffset = sentence.indexOf("[POSP]");
        }
        if (endOffset == -1 || endOffset < startOffset) {
            endOffset = sentence.length() - 1;
        }
        sScope = sentence.substring(startOffset, endOffset + 1);
    }

    // Get the scope of the negation for POST and POSP
    if (sentence.contains("[POST]") || sentence.contains("[POSP]")) {
        int endOffset = sentence.lastIndexOf("[POST]");
        if (endOffset == -1) {
            endOffset = sentence.lastIndexOf("[POSP]");
        }

        int startOffset = sentence.lastIndexOf("[CONJ]");
        if (startOffset == -1) {
            startOffset = sentence.lastIndexOf("[PSEU]");
        }
        if (startOffset == -1) {
            startOffset = sentence.lastIndexOf("[PREN]");
        }
        if (startOffset == -1) {
            startOffset = sentence.lastIndexOf("[PREP]");
        }
        if (startOffset == -1) {
            startOffset = 0;
        }
        sScope = sentence.substring(startOffset, endOffset);
    }

    // Classify to: negated/possible/affirmed
    if (sentence.contains("[NEGATED]")) {
        sentence = sentence + "\t" + "negated" + "\t" + sScope;
    } else if (sentence.contains("[POSSIBLE]")) {
        sentence = sentence + "\t" + "possible" + "\t" + sScope;
    } else {
        sentence = sentence + "\t" + "affirmed" + "\t" + sScope;
    }

    sToReturn = sentence;
    System.out.println(sToReturn);
}

From source file:net.longfalcon.newsj.Releases.java

private String fixRegex(String badRegex) {
    badRegex = badRegex.trim();//from  w  ww  .  j  av  a2  s  .  c o  m
    String findBadNamesRegex = "\\?P\\<(\\w+)\\>"; // fix bad grouping syntax
    Pattern pattern = Pattern.compile(findBadNamesRegex);
    Matcher matcher = pattern.matcher(badRegex);
    String answer = badRegex;
    if (matcher.find()) {
        answer = matcher.replaceAll("?<$1>");
    }

    if (answer.startsWith("/")) {
        answer = answer.substring(1);
    }

    if (answer.endsWith("/i")) { // TODO: case insensitive regexes are not properly created
        answer = answer.substring(0, answer.length() - 2);
    } else if (answer.endsWith("/")) {
        answer = answer.substring(0, answer.length() - 1);
    }

    return answer;
}

From source file:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java

private void maskSensitiveInfo(EsbMessage em, EsbMessageEntity eme) {
    em.setPayload(em.getPayload().replaceAll("\n", ""));
    em.setPayload(em.getPayload().replaceAll("\r", ""));
    em.setPayload(em.getPayload().replaceAll("\t", ""));
    em.setPayload(em.getPayload().replaceAll(">\\s*<", "><"));
    Map<String, String> matchedConfiguration = matchCriteria(em, getPartiallyViewableMessages());
    if (matchedConfiguration != null) {
        String parentTag = matchedConfiguration.get("sensitiveTag");
        Pattern pattern = Pattern
                .compile("<(" + parentTag + ")>((?!<(" + parentTag + ")>).)*</(" + parentTag + ")>");
        Matcher matcher = pattern.matcher(em.getPayload());
        List<String> sensitiveInformation = new ArrayList<>();
        while (matcher.find()) {
            sensitiveInformation.add(matcher.group(0));
        }//  w  w w  .jav  a  2  s  . c  om
        matcher.reset();
        String maskedText = matcher.replaceAll("<$1>" + matchedConfiguration.get("replacementText") + "</$1>");
        eme.setErrorSensitiveInfo(
                ConversionUtility.convertToEsbMessageSensitiveInfo(getEncryptor(), eme, sensitiveInformation));
        eme.setPayload(maskedText);
    }
}

From source file:ca.uhn.hl7v2.testpanel.model.msg.Hl7V2MessageCollection.java

/**
 * Write the messages to an output stream
 *//*w w  w.  j  a  va 2s .c  om*/
public void writeToFile(Writer theWriter, boolean theSelectedSaveStripComments,
        LineEndingsEnum theSelectedLineEndings) throws IOException {
    String toWrite = mySourceMessage;

    if (theSelectedSaveStripComments) {
        switch (myEncoding) {
        case ER_7:

            Pattern p = Pattern.compile("(^|\\r)\\s*#[^\\r]*");
            Matcher m = p.matcher(toWrite);
            toWrite = m.replaceAll("").trim() + "\r";

            p = Pattern.compile("\\r\\s*\\r");
            m = p.matcher(toWrite);
            toWrite = m.replaceAll("\r");

            break;
        }
    }

    toWrite = fixLineEndings(toWrite, theSelectedLineEndings);

    theWriter.append(toWrite);
}

From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java

/**
 * This method is called during initialization and assembles the {@link PreparedStatement}-member
 * {@link #_retrievalStatement} used for data retrieval according to the configuration in the {@link Selections}
 * -attribute of the {@link DataSourceConnectionConfig}. If grouping is enabled in the
 * {@link DataSourceConnectionConfig} the {@link #prepareGrouping()}-method is called.
 * //from w  ww  .j  a va 2  s.  co  m
 * @throws CrawlerCriticalException
 *           If the {@link PreparedStatement} could not be created on the {@link #_connection}
 * 
 */
private void prepareRetrievalStatement() throws CrawlerCriticalException {

    String retrievalSql = _process.getSelections().getSQL();
    retrievalSql = retrievalSql.trim();

    if (_process.getSelections().getGrouping() != null) {
        prepareGrouping();
        _log.debug("Transforming SQL passed from index: [" + retrievalSql + "]");
        final Pattern groupingPlaceholderPattern = Pattern.compile("%\\d\\d(min|max)");
        final Matcher matcher = groupingPlaceholderPattern.matcher(retrievalSql);
        final String transformedSQL = matcher.replaceAll("?");
        _log.debug("Using transformed SQL for PreparedStatement: [" + transformedSQL + "]");
        retrievalSql = transformedSQL;
    }

    try {
        _retrievalStatement = _connection.prepareStatement(retrievalSql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

    } catch (final SQLException e) {
        throw new CrawlerCriticalException("Failed to create statement on database connection", e);
    }

}