List of usage examples for java.util.regex Matcher appendTail
public StringBuilder appendTail(StringBuilder sb)
From source file:org.silverpeas.settings.file.ModifText.java
protected String analyseLine(String line, ElementModif modification) { StringBuffer resStr = new StringBuffer(); if (modification instanceof RegexpElementMotif) { RegexpElementMotif emv = (RegexpElementMotif) modification; Pattern pattern = emv.getPattern(); Matcher match = pattern.matcher(line); while (match.find()) { match.appendReplacement(resStr, emv.getRemplacement()); }//from w w w . j a v a2s.c o m match.appendTail(resStr); } else { // remplace uniquement la derniere occurence de chaque ligne int res = line.lastIndexOf(modification.getSearch()); if (res != -1) { resStr.append(line.substring(0, res)).append(modification.getModif()) .append(line.substring((res + modification.getSearch().length()), line.length())); } } return resStr.toString().trim(); }
From source file:org.cesecore.config.ConfigurationHolder.java
private static String interpolate(final String orderString) { final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}"); final Matcher m = PATTERN.matcher(orderString); final StringBuffer sb = new StringBuffer(orderString.length()); m.reset();// w w w.ja v a2 s . c om while (m.find()) { // when the pattern is ${identifier}, group 0 is 'identifier' final String key = m.group(1); final String value = getExpandedString(key); // if the pattern does exists, replace it by its value // otherwise keep the pattern ( it is group(0) ) if (value != null) { m.appendReplacement(sb, value); } else { // I'm doing this to avoid the backreference problem as there will be a $ // if I replace directly with the group 0 (which is also a pattern) m.appendReplacement(sb, ""); final String unknown = m.group(0); sb.append(unknown); } } m.appendTail(sb); return sb.toString(); }
From source file:org.silverpeas.file.ModifText.java
protected String analyseLine(String line, ElementModif modification) { StringBuffer resStr = new StringBuffer(); if (modification instanceof RegexpElementMotif) { RegexpElementMotif emv = (RegexpElementMotif) modification; Pattern pattern = emv.getPattern(); Matcher match = pattern.matcher(line); while (match.find()) { match.appendReplacement(resStr, emv.getRemplacement()); }/*from ww w. j a v a2 s . c o m*/ match.appendTail(resStr); } else { ElementModif em = modification; // remplace uniquement la derniere occurence de chaque ligne int res = line.lastIndexOf(em.getSearch()); if (res != -1) { resStr.append(line.substring(0, res)).append(em.getModif()) .append(line.substring((res + em.getSearch().length()), line.length())); } } return resStr.toString().trim(); }
From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java
/** * @param input/* w w w .j av a 2 s . c om*/ * @return String */ public static String toLowerHTML(String input) { Pattern genericPattern = Pattern.compile(GENERIC_TAG_PATTERN); Matcher genericMatcher = genericPattern.matcher(input); StringBuffer inputBuffer = new StringBuffer(); while (genericMatcher.find()) { String openBracket = genericMatcher.group(1); String slash = genericMatcher.group(2); String tagName = genericMatcher.group(3); String trailing = genericMatcher.group(4); if (!"HTML".equals(tagName)) { tagName = tagName.toLowerCase(); } genericMatcher.appendReplacement(inputBuffer, escapeBackreference(openBracket + slash + tagName + trailing)); } genericMatcher.appendTail(inputBuffer); return inputBuffer.toString(); }
From source file:com.cubusmail.mail.text.MessageTextUtil.java
/** * Convert a plaint text to html.//from w w w .jav a2 s . c om * * @param plainText * @return */ public static String convertPlainText2Html(String plainText, MessageTextMode mode) { try { plainText = HtmlUtils.htmlEscape(plainText).replaceAll(REPL_LINEBREAK, HTML_BR); final Matcher m = PATTERN_HREF.matcher(plainText); final StringBuffer sb = new StringBuffer(plainText.length()); final StringBuilder tmp = new StringBuilder(256); while (m.find()) { final String nonHtmlLink = m.group(1); if ((nonHtmlLink == null) || (hasSrcAttribute(plainText, m.start(1)))) { m.appendReplacement(sb, Matcher.quoteReplacement(checkTarget(m.group()))); } else { tmp.setLength(0); m.appendReplacement(sb, tmp.append("<a href=\"").append( (nonHtmlLink.startsWith("www") || nonHtmlLink.startsWith("news") ? "http://" : "")) .append("$1\" target=\"_blank\">$1</a>").toString()); } } m.appendTail(sb); if (mode == MessageTextMode.DISPLAY) { sb.insert(0, "<p style=\"font-family: monospace; font-size: 10pt;\">"); sb.append("</p>"); } return sb.toString(); } catch (final Exception e) { log.error(e.getMessage(), e); } catch (final StackOverflowError error) { log.error(StackOverflowError.class.getName(), error); } return plainText; }
From source file:com.vsct.dt.hesperides.resources.KeyValueValorisation.java
private String replaceWithPattern(final String s, final Pattern p, final Function<Matcher, String> replacement) { Matcher matcher = p.matcher(s); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, replacement.apply(matcher)); }//from w w w . j ava 2 s . co m matcher.appendTail(sb); return sb.toString(); }
From source file:com.yukthitech.utils.MessageFormatter.java
/** * Replaces the args values in "message" using patterns mentioned below and same will be returned. * /*w w w. java2 s. c o m*/ * {} will match with the current index argument. If index is greater than provided values then <undefined> string will be used. * {<idx>} can be used to refer to argument at particular index. Helpful in building messages which uses same argument multiple times. * * @param message Message string with expressions * @param args Values for expression * @return Formatted string */ public static String format(String message, Object... args) { //when message is null, return null if (message == null) { return null; } //when args is null, assume empty values if (args == null) { args = new Object[0]; } Matcher matcher = PARAM_PATTERN.matcher(message); StringBuffer buffer = new StringBuffer(); int loopIndex = 0; int argIndex = 0; Object arg = null; //loop through pattern matches while (matcher.find()) { //if index is mentioned in pattern if (org.apache.commons.lang3.StringUtils.isNotBlank(matcher.group(1))) { argIndex = Integer.parseInt(matcher.group(1)); } //if index is not specified, use current loop index else { argIndex = loopIndex; } //if the index is within provided arguments length if (argIndex < args.length) { arg = args[argIndex]; } //if the index is greater than available values else { arg = UNDEFINED; } //if argument value is null if (arg == null) { arg = "null"; } arg = Matcher.quoteReplacement(arg.toString()); matcher.appendReplacement(buffer, arg.toString()); loopIndex++; } matcher.appendTail(buffer); return buffer.toString(); }
From source file:nl.ivonet.epub.strategy.epub.CommentRemovalStrategy.java
@Override public void execute(final Epub epub) { LOG.debug("Applying {} on [{}]", getClass().getSimpleName(), epub.getOrigionalFilename()); final List<Resource> htmlResources = epub.getContents().stream() .filter(HtmlCorruptDetectionStrategy::isHtml).collect(Collectors.toList()); for (final Resource content : htmlResources) { try {/* w w w . j a v a 2 s. com*/ final String html = IOUtils.toString(content.getReader()); final Matcher matcher = PAT.matcher(html); final StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, ""); } matcher.appendTail(sb); content.setData(sb.toString().getBytes()); } catch (IOException e) { epub.addDropout(Dropout.READ_ERROR); } catch (IllegalArgumentException e) { epub.addDropout(Dropout.KEPBUB); } } }
From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java
/** * Process a path, and can return a list of path, according to the variable (she will go a list of values). * @param path/* w w w . j a v a 2s .co m*/ * @return * @throws Exception */ public static String[] processPathVariables(String path, TemplateDataGroup dataGroup) throws Exception { StringBuffer replaceResult = new StringBuffer(); // ---SEARCH FOR stringUtils String regexStringUtils = "\\$\\{stringUtils.*?\\(.*?\\)\\}"; // Compile regular expression Pattern patternStringUtils = Pattern.compile(regexStringUtils); // Create Matcher Matcher matcherStringUtils = patternStringUtils.matcher(path); // Find occurrences while (matcherStringUtils.find()) { String variable = matcherStringUtils.group(); // Variables HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); velocityVariables.put("data", dataGroup); TemplateEngine templateEngine = VelocityTemplateEngine.getInstance(); String vmResult = templateEngine.runInLine(variable, velocityVariables); matcherStringUtils.appendReplacement(replaceResult, vmResult); } matcherStringUtils.appendTail(replaceResult); path = replaceResult.toString(); replaceResult = new StringBuffer(); // ---SEARCH FOR VARIABLE data String regexVariable = "\\$\\{.*?\\}"; Map<String, String[]> mapVariableToDuplicateResult = new HashMap<String, String[]>(); // Compile regular expression Pattern patternVariable = Pattern.compile(regexVariable); // Create Matcher Matcher matcherVariable = patternVariable.matcher(path); // Find occurrences while (matcherVariable.find()) { String variable = matcherVariable.group(); variable = variable.replaceAll("\\$\\{", "").replaceAll("\\}", ""); // variable = variable.substring(2, variable.length()-1); //remove ${ } // replace a list of matches Map<String, Object> objects = new HashMap<String, Object>(); objects.put("data.config", dataGroup.getConfig()); objects.put("data.crud", dataGroup.getCrud()); objects.put("data.bundle", dataGroup.getBundle()); String[] values = BuildManagerUtil.readValue(variable, objects); if (values.length == 1) { // one value matcherVariable.appendReplacement(replaceResult, values[0]); } else if (values.length > 1) { // list of values mapVariableToDuplicateResult.put(variable, values); // guarda todas as // vriaveis do tipo // LIST do path } } matcherVariable.appendTail(replaceResult); // s permitido uma vriavel do tipo list no nas vriaveis if (mapVariableToDuplicateResult.size() > 1) { throw new Exception("Template error: Alone it is permitted one variable of the kind LIST in the paths"); } // return results // process list of variables, or return if (mapVariableToDuplicateResult.size() == 1) { // rules of the list of // values for the variable // (existe uma vriavel do // tipo list) List<String> results = new ArrayList<String>(); // grava os resultados for (String variable : mapVariableToDuplicateResult.keySet()) { // loop // nas // variaveis // do tipo // list // (que // uma s) String[] values = mapVariableToDuplicateResult.get(variable); // pega os // valores // vlidos // para a // variavel // do tipo // list // (valores // que // devem // entrar // no // lugar // da // vriavel // list) for (String value : values) { results.add(replaceResult.toString().replaceAll("\\$\\{" + variable + "\\}", value)); // adiciona // um // path // novo // para // cada // valor // que // tem // que // ser // substituido } } // transforma o list em array de string String[] values = new String[results.size()]; for (int i = 0; i < results.size(); i++) { values[i] = results.get(i).toString(); } return values; } else if (mapVariableToDuplicateResult.size() == 0 && !replaceResult.toString().equals("")) { // there // is // does // not // list // of // values, // is // simple // replace return new String[] { replaceResult.toString() }; } // no encontrou resultados / not matches found return new String[] { path }; }
From source file:org.onebusaway.webapp.actions.where.ServiceAlertAction.java
private String htmlify(String content) { Pattern p = Pattern.compile("(http://[^\\s]+)"); Matcher m = p.matcher(content); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "<a href=\"" + m.group(1) + "\">" + m.group(1) + "</a> "); }// w w w . j a v a 2 s. co m m.appendTail(sb); content = sb.toString(); content = content.replaceAll("\r\n", "<br/>"); content = content.replaceAll("\n", "<br/>"); return content; }