List of usage examples for java.util.regex Matcher appendTail
public StringBuilder appendTail(StringBuilder sb)
From source file:org.nuclos.common2.StringUtils.java
/** * Splits the given input sequence around matches of the given pattern but * also include the matches in the result. * All strings at odd indices are matches of the given pattern, all strings * at even indices are the splitted text fragments. *///from w ww . j a v a 2 s .c om public static String[] splitWithMatches(Pattern pattern, int group, CharSequence input) { Matcher m = pattern.matcher(input); List<String> list = new ArrayList<String>(); while (m.find()) { StringBuffer sb = new StringBuffer(); m.appendReplacement(sb, ""); list.add(sb.toString()); list.add(m.group(group)); } StringBuffer sb = new StringBuffer(); m.appendTail(sb); list.add(sb.toString()); return list.toArray(new String[list.size()]); }
From source file:org.openpplsoft.sql.StmtLibrary.java
private static String processAndExpandWhereStr(final String rootAlias, final String whereStr) { String newWhereStr = whereStr; // Expand any %EffDtCheck meta-SQL final Matcher effDtCheckMatcher = effDtCheckPattern.matcher(newWhereStr); while (effDtCheckMatcher.find()) { final String effDtCheckRecord = effDtCheckMatcher.group(1); // Do not use group 2 (contains whitespace preceding the optional subquery alias) String effDtSubqueryAlias = effDtCheckMatcher.group(3); final String effDtRootAlias = effDtCheckMatcher.group(4); String effDtBound = effDtCheckMatcher.group(5); if (!rootAlias.equals(effDtRootAlias)) { throw new OPSVMachRuntimeException( "While preparing fill query, " + "found %EffDtCheck that has a root alias (" + effDtRootAlias + ") different than expected (" + rootAlias + ")."); }//from w w w . j a v a2 s . c om // If subquery alias is not specified, use name of record being checked. if (effDtSubqueryAlias == null) { effDtSubqueryAlias = effDtCheckRecord; } StringBuilder effDtSubqueryBuilder = new StringBuilder("SELECT MAX(EFFDT) FROM ") .append(effDtCheckRecord).append(' ').append(effDtSubqueryAlias).append(" WHERE"); final Record effDtRecord = DefnCache.getRecord(effDtCheckRecord); for (final Map.Entry<String, RecordField> cursor : effDtRecord.getFieldTable().entrySet()) { final RecordField rf = cursor.getValue(); if (rf.isKey() && !rf.getFldName().equals("EFFDT")) { effDtSubqueryBuilder.append(' ').append(effDtSubqueryAlias).append('.').append(rf.getFldName()) .append('=').append(effDtRootAlias).append('.').append(rf.getFldName()).append(" AND"); } } // If the effDtBound is not a meta-sql construct, it will not // be wrapped with TO_DATE later in this function, so wrap it now. if (effDtBound.length() == 0 || effDtBound.charAt(0) != '%') { effDtBound = "TO_DATE(" + effDtBound + ",'YYYY-MM-DD')"; } effDtSubqueryBuilder.append(' ').append(effDtSubqueryAlias).append(".EFFDT<=").append(effDtBound); newWhereStr = effDtCheckMatcher .replaceAll(effDtRootAlias + ".EFFDT=(" + effDtSubqueryBuilder.toString() + ")"); } // Replace occurrences of %DATEIN/DateIn with TO_DATE(*,'YYYY-MM-DD') final Matcher dateInMatcher = dateInPattern.matcher(newWhereStr); final StringBuffer dateInSb = new StringBuffer(); while (dateInMatcher.find()) { dateInMatcher.appendReplacement(dateInSb, "TO_DATE(" + dateInMatcher.group(2) + ",'YYYY-MM-DD')"); } dateInMatcher.appendTail(dateInSb); newWhereStr = dateInSb.toString(); // Replace occurrences of %CurrentDateIn final Matcher currDateInMatcher = currDateInPattern.matcher(newWhereStr); newWhereStr = currDateInMatcher.replaceAll("TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')"); return newWhereStr; }
From source file:org.kalypso.ui.editor.styleeditor.symbolizer.StringToParameterValueTypeConverter.java
private String matchTail(final Matcher matcher) { final StringBuffer buf = new StringBuffer(); matcher.appendTail(buf); return buf.toString(); }
From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java
private static String changeImageUrls(String contextPath, String cssSourceCode, String cssPath) { Matcher matcher = CSS_URL_PATTERN.matcher(cssSourceCode); StringBuffer sb = new StringBuffer(); Path basePath = Paths.get(contextPath + cssPath); while (matcher.find()) { String url = matcher.group(2); url = url.trim();//from w w w . jav a2 s .c o m if (url.equals("#default#VML") || url.startsWith("data:")) { continue; } Path pa = basePath.resolveSibling(url).normalize(); matcher.appendReplacement(sb, "$1" + pa.toString().replace("\\", "/") + "$3$4"); } matcher.appendTail(sb); return sb.toString(); }
From source file:org.j2eespider.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.ja v a 2s. com * @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:com.yukthi.utils.MessageFormatter.java
/** * Replaces the args values in "message" using patterns mentioned below and same will be returned. * /* w ww.jav a2s. c om*/ * {} 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 (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"; } matcher.appendReplacement(buffer, arg.toString()); loopIndex++; } matcher.appendTail(buffer); return buffer.toString(); }
From source file:net.opentsdb.tools.ConfigArgP.java
/** * Replaces all matched tokens with the matching system property value or a configured default * @param text The text to process// w w w . jav a 2 s.co m * @return The substituted string */ public static String tokenReplaceSysProps(CharSequence text) { if (text == null) return null; Matcher m = SYS_PROP_PATTERN.matcher(text); StringBuffer ret = new StringBuffer(); while (m.find()) { String replacement = decodeToken(m.group(1), m.group(2) == null ? "<null>" : m.group(2)); if (replacement == null) { throw new IllegalArgumentException( "Failed to fill in SystemProperties for expression with no default [" + text + "]"); } if (IS_WINDOWS) { replacement = replacement.replace(File.separatorChar, '/'); } m.appendReplacement(ret, replacement); } m.appendTail(ret); return ret.toString(); }
From source file:org.ejbca.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();//from w w w.ja v a2 s .c o m 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.apache.flink.table.runtime.functions.SqlFunctionUtils.java
/** * Returns a string resulting from replacing all substrings that match the regular * expression with replacement.// ww w . ja va 2s. co m */ public static String regexpReplace(String str, String regex, String replacement) { if (regex.isEmpty()) { return str; } try { // we should use StringBuffer here because Matcher only accept it StringBuffer sb = new StringBuffer(); Matcher m = REGEXP_PATTERN_CACHE.get(regex).matcher(str); while (m.find()) { m.appendReplacement(sb, replacement); } m.appendTail(sb); return sb.toString(); } catch (Exception e) { LOG.error(String.format("Exception in regexpReplace('%s', '%s', '%s')", str, regex, replacement), e); // return null if exception in regex replace return null; } }
From source file:com.hexidec.ekit.component.HTMLTableUtilities.java
public static String separaTabelasDeParagrafos(String str) { Matcher m = pTabelaEmParagrafo.matcher(str); if (!m.find()) { return str; }//from ww w.j a va2s .c o m StringBuffer sb = new StringBuffer(); StringBuffer trecho; String pOpen, strBefore, tOpen, tBody, strAfter; do { trecho = new StringBuffer(); pOpen = m.group(1); strBefore = m.group(2); tOpen = m.group(3); tBody = m.group(4); strAfter = m.group(5); if (!StringUtils.isEmpty(strBefore.trim())) { trecho.append(pOpen); trecho.append(strBefore); trecho.append("</p>"); } trecho.append(tOpen); trecho.append(tBody); trecho.append("</table>"); if (!StringUtils.isEmpty(strAfter.trim())) { trecho.append(pOpen); trecho.append(strAfter); trecho.append("</p>"); } m.appendReplacement(sb, Matcher.quoteReplacement(trecho.toString())); } while (m.find()); m.appendTail(sb); return sb.toString(); }