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:it.drwolf.ridire.utility.RIDIREPlainTextCleaner.java

private String substitute(String original, String regex, String subst) {
    Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
    Matcher m = p.matcher(original);
    return m.replaceAll(subst);
}

From source file:com.octo.mbo.domain.ApproachingMatcher.java

/**
 * First ignore additional spaces "........"
 * @param inputString string to normalize
 * @return inputString without more than one consecutive space
 *//*from  w w  w  .ja v a 2  s  .  c o m*/
public String normalize(String inputString) {
    assert inputString != null;

    Matcher m = p.matcher(inputString);
    return m.replaceAll(" ");
}

From source file:org.kuali.rice.kns.util.WebUtils.java

/**
 * Excapes out HTML to prevent XSS attacks, and replaces the following
 * strings to allow for a limited set of HTML tags
 * //from w  w  w . ja va 2s . c  om
 * <li>[X] and [/X], where X represents any 1 or 2 letter string may be used
 * to specify the equivalent tag in HTML (i.e. &lt;X&gt; and &lt;/X&gt;) <li>
 * [font COLOR], where COLOR represents any valid html color (i.e. color
 * name or hexcode preceeded by #) will be filtered into &lt;font
 * color="COLOR"/&gt; <li>[/font] will be filtered into &lt;/font&gt; <li>
 * [table CLASS], where CLASS gives the style class to use, will be filter
 * into &lt;table class="CLASS"/&gt; <li>[/table] will be filtered into
 * &lt;/table&gt; <li>[td CLASS], where CLASS gives the style class to use,
 * will be filter into &lt;td class="CLASS"/&gt;
 * 
 * @param inputString
 * @return
 */
public static String filterHtmlAndReplaceRiceMarkup(String inputString) {
    String outputString = StringEscapeUtils.escapeHtml(inputString);
    // string has been escaped of all <, >, and & (and other characters)

    Map<String, String> findAndReplacePatterns = new LinkedHashMap<String, String>();

    // now replace our rice custom markup into html

    // DON'T ALLOW THE SCRIPT TAG OR ARBITRARY IMAGES/URLS/ETC. THROUGH

    //strip out instances where javascript precedes a URL
    findAndReplacePatterns.put("\\[a ((javascript|JAVASCRIPT|JavaScript).+)\\]", "");
    //turn passed a href value into appropriate tag
    findAndReplacePatterns.put("\\[a (.+)\\]", "<a href=\"$1\">");
    findAndReplacePatterns.put("\\[/a\\]", "</a>");

    // filter any one character tags
    findAndReplacePatterns.put("\\[([A-Za-z])\\]", "<$1>");
    findAndReplacePatterns.put("\\[/([A-Za-z])\\]", "</$1>");
    // filter any two character tags
    findAndReplacePatterns.put("\\[([A-Za-z]{2})\\]", "<$1>");
    findAndReplacePatterns.put("\\[/([A-Za-z]{2})\\]", "</$1>");
    // filter the font tag
    findAndReplacePatterns.put("\\[font (#[0-9A-Fa-f]{1,6}|[A-Za-z]+)\\]", "<font color=\"$1\">");
    findAndReplacePatterns.put("\\[/font\\]", "</font>");
    // filter the table tag
    findAndReplacePatterns.put("\\[table\\]", "<table>");
    findAndReplacePatterns.put("\\[table ([A-Za-z]+)\\]", "<table class=\"$1\">");
    findAndReplacePatterns.put("\\[/table\\]", "</table>");
    // fiter td with class
    findAndReplacePatterns.put("\\[td ([A-Za-z]+)\\]", "<td class=\"$1\">");

    for (String findPattern : findAndReplacePatterns.keySet()) {
        Pattern p = Pattern.compile(findPattern);
        Matcher m = p.matcher(outputString);
        if (m.find()) {
            String replacePattern = findAndReplacePatterns.get(findPattern);
            outputString = m.replaceAll(replacePattern);
        }
    }

    return outputString;
}

From source file:org.kuali.kfs.kns.util.WebUtils.java

/**
 * Excapes out HTML to prevent XSS attacks, and replaces the following
 * strings to allow for a limited set of HTML tags
 * <p>//from   w ww. j a v a  2 s  .  c  o m
 * <li>[X] and [/X], where X represents any 1 or 2 letter string may be used
 * to specify the equivalent tag in HTML (i.e. &lt;X&gt; and &lt;/X&gt;) <li>
 * [font COLOR], where COLOR represents any valid html color (i.e. color
 * name or hexcode preceeded by #) will be filtered into &lt;font
 * color="COLOR"/&gt; <li>[/font] will be filtered into &lt;/font&gt; <li>
 * [table CLASS], where CLASS gives the style class to use, will be filter
 * into &lt;table class="CLASS"/&gt; <li>[/table] will be filtered into
 * &lt;/table&gt; <li>[td CLASS], where CLASS gives the style class to use,
 * will be filter into &lt;td class="CLASS"/&gt;
 *
 * @param inputString
 * @return
 */
public static String filterHtmlAndReplaceRiceMarkup(String inputString) {
    String outputString = StringEscapeUtils.escapeHtml4(inputString);
    // string has been escaped of all <, >, and & (and other characters)

    Map<String, String> findAndReplacePatterns = new LinkedHashMap<String, String>();

    // now replace our rice custom markup into html

    // DON'T ALLOW THE SCRIPT TAG OR ARBITRARY IMAGES/URLS/ETC. THROUGH

    //strip out instances where javascript precedes a URL
    findAndReplacePatterns.put("\\[a ((javascript|JAVASCRIPT|JavaScript).+)\\]", "");
    //turn passed a href value into appropriate tag
    findAndReplacePatterns.put("\\[a (.+)\\]", "<a href=\"$1\">");
    findAndReplacePatterns.put("\\[/a\\]", "</a>");

    // filter any one character tags
    findAndReplacePatterns.put("\\[([A-Za-z])\\]", "<$1>");
    findAndReplacePatterns.put("\\[/([A-Za-z])\\]", "</$1>");
    // filter any two character tags
    findAndReplacePatterns.put("\\[([A-Za-z]{2})\\]", "<$1>");
    findAndReplacePatterns.put("\\[/([A-Za-z]{2})\\]", "</$1>");
    // filter the font tag
    findAndReplacePatterns.put("\\[font (#[0-9A-Fa-f]{1,6}|[A-Za-z]+)\\]", "<font color=\"$1\">");
    findAndReplacePatterns.put("\\[/font\\]", "</font>");
    // filter the table tag
    findAndReplacePatterns.put("\\[table\\]", "<table>");
    findAndReplacePatterns.put("\\[table ([A-Za-z]+)\\]", "<table class=\"$1\">");
    findAndReplacePatterns.put("\\[/table\\]", "</table>");
    // fiter td with class
    findAndReplacePatterns.put("\\[td ([A-Za-z]+)\\]", "<td class=\"$1\">");

    for (String findPattern : findAndReplacePatterns.keySet()) {
        Pattern p = Pattern.compile(findPattern);
        Matcher m = p.matcher(outputString);
        if (m.find()) {
            String replacePattern = findAndReplacePatterns.get(findPattern);
            outputString = m.replaceAll(replacePattern);
        }
    }

    return outputString;
}

From source file:io.dataapps.chlorine.pattern.RegexFinder.java

private String replace(String input, String replacement) {
    Matcher matcher = pattern.matcher(input);
    return matcher.replaceAll(replacement);
}

From source file:org.apdplat.search.util.baidu.JsoupBaiduInfoUtil.java

/**
* @author JONE/*from www .  j a  v  a  2  s .  co  m*/
* @return String
* @time 2013-11-11
* @description ??13100
*/
public String getResultsCount() {
    String resultsCountText = this.getResultsCountText();
    if (StringUtils.isEmpty(StringUtils.trim(resultsCountText))) {
        return "";
    }
    String regEx = "[^0-9]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(resultsCountText);
    String totalCount = m.replaceAll("").trim();
    baiduModels.setTotal(Integer.parseInt(totalCount));
    return totalCount;
}

From source file:org.dspace.app.statistics.LogAnalyser.java

/**
 * Take a search query string and pull out all of the meaningful information
 * from it, giving the results in the form of a String array, a single word
 * to each element//from  ww w.jav a 2 s .  c om
 * 
 * @param   query   the search query to be analysed
 *
 * @return          the string array containing meaningful search terms
 */
public static String[] analyseQuery(String query) {
    // register our standard loop counter
    int i = 0;

    // make the query string totally lower case, to ensure we don't miss out
    // on matches due to capitalisation
    query = query.toLowerCase();

    // now perform successive find and replace operations using pre-defined
    // global regular expressions
    Matcher matchQuery = queryRX.matcher(query);
    query = matchQuery.replaceAll(" ");

    Matcher matchCollection = collectionRX.matcher(query);
    query = matchCollection.replaceAll(" ");

    Matcher matchCommunity = communityRX.matcher(query);
    query = matchCommunity.replaceAll(" ");

    Matcher matchResults = resultsRX.matcher(query);
    query = matchResults.replaceAll(" ");

    Matcher matchTypes = typeRX.matcher(query);
    query = matchTypes.replaceAll(" ");

    Matcher matchChars = excludeCharRX.matcher(query);
    query = matchChars.replaceAll(" ");

    Matcher matchWords = wordRX.matcher(query);
    query = matchWords.replaceAll(" ");

    Matcher single = singleRX.matcher(query);
    query = single.replaceAll(" ");

    // split the remaining string by whitespace, trim and stuff into an
    // array to be returned
    StringTokenizer st = new StringTokenizer(query);
    String[] words = new String[st.countTokens()];
    for (i = 0; i < words.length; i++) {
        words[i] = st.nextToken().trim();
    }

    // FIXME: some single characters are still slipping through the net;
    // why? and how do we fix it?
    return words;
}

From source file:org.brushingbits.jnap.persistence.hibernate.QueryPagingSetup.java

public int countTotal() {
    // build the count query
    String countHql = query.getQueryString();
    int indexOfFromClause = countHql.toLowerCase().indexOf("from");
    countHql = countHql.substring(indexOfFromClause, countHql.length());
    countHql = "select count(*) " + countHql;

    // remove 'order by' clauses if present
    Matcher orderByMatcher = ORDER_BY_REMOVE_REGEXP.matcher(countHql);
    countHql = orderByMatcher.replaceAll(StringUtils.EMPTY);

    Query countQuery = this.currentSession.createQuery(countHql);
    QueryUtils.setParameters(countQuery, this.queryParams);
    return ((Number) countQuery.uniqueResult()).intValue();
}

From source file:architecture.common.model.impl.UserModelImpl.java

public static String formatUsername(String username) {
    if (username == null)
        return null;

    boolean allowWhiteSpace = false;

    try {//w ww .  ja v  a2 s.c o  m
        ConfigService config = Bootstrap.getBootstrapComponent(ConfigService.class);
        allowWhiteSpace = config.getApplicationBooleanProperty("username.allowWhiteSpace", false);
    } catch (Throwable ignore) {
    }

    if (allowWhiteSpace) {
        String formattedUsername = "";
        Pattern p = Pattern.compile("\\s+");
        Matcher m = p.matcher(username.trim());
        if (m.find()) {
            formattedUsername = m.replaceAll(" ");
            username = formattedUsername;
        }
    } else {
        username = StringUtils.stripToEmpty(username);
    }
    return username;
}

From source file:com.seer.datacruncher.spring.MacrosValidateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String varList = request.getParameter("varList");
    String rule = request.getParameter("rule");
    Long schemaId = Long.valueOf(request.getParameter("schemaId"));
    if (rule == null) {
        throw new IllegalArgumentException("MacrosValidateController: null parameter 'rule'");
    }/*from   w ww . ja v a2  s  .c om*/
    String success = "true";
    Map<String, String> resMap = new HashMap<String, String>();
    if (rule.trim().isEmpty()) {
        success = "false";
        resMap.put("errMsg", I18n.getMessage("error.macro.emptyRule"));
    }
    Pattern pattern = Pattern.compile(MacroRulesValidation.MACRO_SQL_VALIDATOR_PATTERN,
            Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(rule);
    rule = matcher.replaceAll("true");
    List<Map<String, String>> list = MacroRulesValidation.parseVars(varList);
    MacroRulesValidation.combineVariableLists(list, schemaId);
    JexlEngine jexl = JexlEngineFactory.getInstance();
    try {
        Expression e = jexl.createExpression(rule);
        JexlContext context = new MapContext();
        for (Map<String, String> m : list) {
            String anyStringDigit = "7";
            context.set(m.get("uniqueName"),
                    JEXLFieldFactory.getField(m.get("fieldType"), anyStringDigit).getValue());
        }
        e.evaluate(context);
    } catch (Exception e1) {
        success = "false";
        resMap.put("errMsg", e1.getMessage() + "\n" + getStackTrace(e1));
    }
    resMap.put("success", success);
    response.getWriter().print(new JSONObject(resMap).toString());
    return null;
}